Skip to content

Commit 2a8e285

Browse files
authored
Add message customization on validator (#17)
1 parent 7eb31d3 commit 2a8e285

File tree

5 files changed

+40
-17
lines changed

5 files changed

+40
-17
lines changed

docs/source/index.md

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,11 @@ def register():
112112
'avatar': ['image', 'dimensions:200x200'],
113113
'username': ['required', 'string', 'min:6'],
114114
}
115-
validator = Validator(rules=rules, request=request)
115+
messages = {
116+
'email.required': 'Yikes! The email is required',
117+
'avatar.dimensions': 'Please provide an avatar with the right dimensions'
118+
}
119+
validator = Validator(rules=rules, messages=messages, request=request)
116120
if validator.passes():
117121
return jsonify({'message': 'Registered!'}), 200
118122
return jsonify(validator.messages()), 400

flask_sieve/translator.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,9 @@ def translated_errors(self):
2626
translated = []
2727
for validation in validations:
2828
if not validation['is_valid']:
29-
custom_message_key = validation['attribute'] + '.' + validation['rule']
30-
if custom_message_key in self._custom_messages:
31-
translated.append(self._custom_messages[custom_message_key])
29+
validation_key = validation['attribute'] + '.' + validation['rule']
30+
if validation_key in self._custom_messages:
31+
translated.append(self._custom_messages[validation_key])
3232
else:
3333
translated.append(self._translate_validation(validation))
3434
if len(translated):
@@ -41,13 +41,13 @@ def _translate_validation(self, validation):
4141
if validation['rule'] in self._size_rules:
4242
message = message[validation['attribute_type']]
4343
message_fields = self._extract_message_fields(message)
44-
fields_to_params = self._zip_fields_to_params(
45-
fields=message_fields,
46-
params=validation['params']
47-
)
44+
fields_to_params = \
45+
self._zip_fields_to_params(fields=message_fields,
46+
params=validation['params'])
4847
for field in message_fields:
4948
if field == ':attribute':
50-
message = message.replace(field, validation['attribute'])
49+
message = message.replace(field, ' '.join([word for word in
50+
validation['attribute'].split('_') if word != '']))
5151
else:
5252
message = message.replace(field, fields_to_params[field])
5353
return message

flask_sieve/validator.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,10 @@
88

99

1010
class Validator:
11-
def __init__(self, rules=None, request=None, custom_handlers=None):
11+
def __init__(self, rules=None, request=None, custom_handlers=None,
12+
messages=None, **kwargs):
1213
self._parser = Parser()
13-
self._translator = Translator()
14+
self._translator = Translator(custom_messages=messages)
1415
self._processor = RulesProcessor()
1516
self._rules = rules or {}
1617
self._custom_handlers = custom_handlers or {}

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
name='flask-sieve',
66
description='A Laravel inspired requests validator for Flask',
77
long_description='Find the documentation at https://flask-sieve.readthedocs.io/en/latest/',
8-
version='1.2.0',
8+
version='1.2.1',
99
url='https://github.com/codingedward/flask-sieve',
1010
license='BSD-2',
1111
author='Edward Njoroge',

tests/test_validator.py

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,19 +11,20 @@ def setUp(self):
1111

1212
def test_translates_validations(self):
1313
self.set_validator_params(
14-
rules={'email': ['required', 'email']},
15-
request={'email': 'invalid_email'},
14+
rules={'email_address': ['required', 'email']},
15+
request={'email_address': 'invalid_email'},
1616
)
1717
self.assertTrue(self._validator.fails())
18-
self.assertIn('valid email', str(self._validator.messages()))
18+
self.assertIn('valid email address', str(self._validator.messages()))
1919

2020
def test_translates_validations_with_param(self):
2121
self.set_validator_params(
22-
rules={'name': ['required', 'string', 'min:6']},
23-
request={'name': 'joe'},
22+
rules={'first_name': ['required', 'string', 'min:6']},
23+
request={'first_name': 'joe'},
2424
)
2525
self.assertTrue(self._validator.fails())
2626
self.assertIn('6 characters', str(self._validator.messages()))
27+
self.assertIn('first name', str(self._validator.messages()))
2728

2829
def test_translates_validations_with_rest_params(self):
2930
self.set_validator_params(
@@ -95,6 +96,23 @@ def test_translates_validations_with_custom_messages(self):
9596
]
9697
}, self._validator.messages())
9798

99+
def test_translates_validations_with_custom_messages_on_constructor(self):
100+
validator = Validator(
101+
rules={'email': ['required', 'email']},
102+
request={'email': ''},
103+
messages={
104+
'email.required': 'Kindly provide the email',
105+
'email.email': 'Whoa! That is not valid',
106+
}
107+
)
108+
self.assertTrue(validator.fails())
109+
self.assertDictEqual({
110+
'email': [
111+
'Kindly provide the email',
112+
'Whoa! That is not valid'
113+
]
114+
}, validator.messages())
115+
98116
def test_translates_validations_with_custom_handler(self):
99117
def validate_odd(value, **kwargs):
100118
return int(value) % 2

0 commit comments

Comments
 (0)