Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New special validator: MultiTypeValidator #21

Open
binaryDiv opened this issue Nov 9, 2021 · 0 comments
Open

New special validator: MultiTypeValidator #21

binaryDiv opened this issue Nov 9, 2021 · 0 comments
Labels
new validator Implementation of a new validator class
Milestone

Comments

@binaryDiv
Copy link
Contributor

binaryDiv commented Nov 9, 2021

Add a special validator where you can specify multiple allowed types and validators associated with them. The validator would first check the type, then call the specified validator, or raise an InvalidTypeError if no validator was specified for this type.

For example, you could build a validator that accepts numbers in different formats (integer 42, float 1.234, decimal string "1.234") like this:

validator = MultiTypeValidator({
    int: IntegerValidator(),
    float: FloatValidator(),
    str: DecimalValidator(),
})

validator.validate(42)       # returns 42 (integer)
validator.validate(1.234)    # returns 1.234 (float)
validator.validate("1.234")  # returns Decimal("1.234")

# Error cases:
validator.validate(False)     # raises InvalidTypeError since no validator for bools was defined
validator.validate("banana")  # decides to use the DecimalValidator, which raises an InvalidDecimalError

Additionally, allow multiple validators to be specified for the same type (e.g. as a list). In that case, if the first validator raises a validation error, the next one is tried. If no validator successfully validates the input, the validation error of the last validator is used.

For example:

validator = MultiTypeValidator({
    str: [
        DecimalValidator(),
        StringValidator(max_length=4),
    ],
})

validator.validate("1.23456789")  # uses DecimalValidator, returns Decimal("1.23456789")
validator.validate("bana")        # DecimalValidator fails, uses StringValidator, returns "bana"
validator.validate("banana")      # DecimalValidator fails, StringValidator fails, raises StringTooLongError
@binaryDiv binaryDiv added the new validator Implementation of a new validator class label Nov 9, 2021
@binaryDiv binaryDiv added this to the 1.0.0 Release milestone Nov 9, 2021
@binaryDiv binaryDiv changed the title New meta validator: MultiTypeValidator New special validator: MultiTypeValidator May 11, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
new validator Implementation of a new validator class
Projects
None yet
Development

No branches or pull requests

1 participant