Deepwalker / trafaret

Ultimate transformation library that supports validation, contexts and aiohttp.
http://trafaret.readthedocs.org/en/latest/
BSD 2-Clause "Simplified" License
177 stars 31 forks source link

How to localize error messages? #119

Open lud4ik opened 3 years ago

Arfey commented 3 years ago

hi. i think that it's not work for the trafaret. if u wanna to do localisation for an error message u can do that via a mapping of errors.

Here docs

import trafaret as t

login_validator = t.Dict({'username': t.String(max_length=10), 'email': t.Email})

try:
    login_validator.check({'username': 'So loooong name', 'email': 'misha'})
except t.DataError as e:
    errors = e.to_struct()

# {
#    'code': 'some_elements_did_not_match',
#    'nested': {
#        'username': {
#            'code': 'long_string',
#            'message': 'String is longer than 10 characters'
#        },
#        'email': {
#            'code': 'is_not_valid_email',
#            'message': 'value is not a valid email address'
#        }
#    }
# }

so with to_struct method u can to get error code and after that generate local error message

from trafaret.codes import LONG_STRING, IS_NOT_VALID_EMAIL

errors_mapper = {
    LONG_STRING: _("message is so long"),
    IS_NOT_VALID_EMAIL: _('is not valid email')
}
def trf_errors_to_local(errors):
    return {
        e: errors_mapper[errors[e]['code']]
        for e in errors
    }

trf_errors_to_local(errors['nested'])

# {'username': 'message is so long', 'email': 'is not valid emai'}

is this enough for your case? 🙂

Deepwalker commented 3 years ago

There is no easy way to do this now. Looks like we should implement one.