Skip to content

Commit

Permalink
Add message customization on validator (#17)
Browse files Browse the repository at this point in the history
  • Loading branch information
codingedward authored Nov 17, 2020
1 parent 7eb31d3 commit 2a8e285
Show file tree
Hide file tree
Showing 5 changed files with 40 additions and 17 deletions.
6 changes: 5 additions & 1 deletion docs/source/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,11 @@ def register():
'avatar': ['image', 'dimensions:200x200'],
'username': ['required', 'string', 'min:6'],
}
validator = Validator(rules=rules, request=request)
messages = {
'email.required': 'Yikes! The email is required',
'avatar.dimensions': 'Please provide an avatar with the right dimensions'
}
validator = Validator(rules=rules, messages=messages, request=request)
if validator.passes():
return jsonify({'message': 'Registered!'}), 200
return jsonify(validator.messages()), 400
Expand Down
16 changes: 8 additions & 8 deletions flask_sieve/translator.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@ def translated_errors(self):
translated = []
for validation in validations:
if not validation['is_valid']:
custom_message_key = validation['attribute'] + '.' + validation['rule']
if custom_message_key in self._custom_messages:
translated.append(self._custom_messages[custom_message_key])
validation_key = validation['attribute'] + '.' + validation['rule']
if validation_key in self._custom_messages:
translated.append(self._custom_messages[validation_key])
else:
translated.append(self._translate_validation(validation))
if len(translated):
Expand All @@ -41,13 +41,13 @@ def _translate_validation(self, validation):
if validation['rule'] in self._size_rules:
message = message[validation['attribute_type']]
message_fields = self._extract_message_fields(message)
fields_to_params = self._zip_fields_to_params(
fields=message_fields,
params=validation['params']
)
fields_to_params = \
self._zip_fields_to_params(fields=message_fields,
params=validation['params'])
for field in message_fields:
if field == ':attribute':
message = message.replace(field, validation['attribute'])
message = message.replace(field, ' '.join([word for word in
validation['attribute'].split('_') if word != '']))
else:
message = message.replace(field, fields_to_params[field])
return message
Expand Down
5 changes: 3 additions & 2 deletions flask_sieve/validator.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@


class Validator:
def __init__(self, rules=None, request=None, custom_handlers=None):
def __init__(self, rules=None, request=None, custom_handlers=None,
messages=None, **kwargs):
self._parser = Parser()
self._translator = Translator()
self._translator = Translator(custom_messages=messages)
self._processor = RulesProcessor()
self._rules = rules or {}
self._custom_handlers = custom_handlers or {}
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
name='flask-sieve',
description='A Laravel inspired requests validator for Flask',
long_description='Find the documentation at https://flask-sieve.readthedocs.io/en/latest/',
version='1.2.0',
version='1.2.1',
url='https://github.com/codingedward/flask-sieve',
license='BSD-2',
author='Edward Njoroge',
Expand Down
28 changes: 23 additions & 5 deletions tests/test_validator.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,20 @@ def setUp(self):

def test_translates_validations(self):
self.set_validator_params(
rules={'email': ['required', 'email']},
request={'email': 'invalid_email'},
rules={'email_address': ['required', 'email']},
request={'email_address': 'invalid_email'},
)
self.assertTrue(self._validator.fails())
self.assertIn('valid email', str(self._validator.messages()))
self.assertIn('valid email address', str(self._validator.messages()))

def test_translates_validations_with_param(self):
self.set_validator_params(
rules={'name': ['required', 'string', 'min:6']},
request={'name': 'joe'},
rules={'first_name': ['required', 'string', 'min:6']},
request={'first_name': 'joe'},
)
self.assertTrue(self._validator.fails())
self.assertIn('6 characters', str(self._validator.messages()))
self.assertIn('first name', str(self._validator.messages()))

def test_translates_validations_with_rest_params(self):
self.set_validator_params(
Expand Down Expand Up @@ -95,6 +96,23 @@ def test_translates_validations_with_custom_messages(self):
]
}, self._validator.messages())

def test_translates_validations_with_custom_messages_on_constructor(self):
validator = Validator(
rules={'email': ['required', 'email']},
request={'email': ''},
messages={
'email.required': 'Kindly provide the email',
'email.email': 'Whoa! That is not valid',
}
)
self.assertTrue(validator.fails())
self.assertDictEqual({
'email': [
'Kindly provide the email',
'Whoa! That is not valid'
]
}, validator.messages())

def test_translates_validations_with_custom_handler(self):
def validate_odd(value, **kwargs):
return int(value) % 2
Expand Down

0 comments on commit 2a8e285

Please sign in to comment.