python-validators / validators

Python Data Validation for Humans™.
MIT License
977 stars 155 forks source link

Return specific reason when ValidationFailure #159

Closed TimonPeng closed 7 months ago

TimonPeng commented 4 years ago

There may be multiple reasons for validation failure:

For example, bank card number:

Can we return True when validation pass, and return fail reason then validation failed, then we can get the specific reason.

card.py

@validator
def visa(value):
    pattern = re.compile(r'^4')

    if not card_number(value):
        return 'Checksum error'

    if not len(value) == 16:
        return 'Length error'

    if not pattern.match(value):
        return 'Not VISA card'

    return True

utils.py

def validator(func, *args, **kwargs):
        value = func(*args, **kwargs)
        if value is not True:
            do something and return the specific reason...
kvesteri commented 4 years ago

Sure! PRs welcome.

yozachar commented 7 months ago

Apologies, the current implementation has made it difficult to pin-point the exact reason for validation failure, without over-complicating the codebase.

Instead the users are provided with the following information, which they can cross-check to debug:

>>> import validators
>>> validators.visa("abcd")
ValidationError(func=visa, args={'value': 'abcd'}