-
Notifications
You must be signed in to change notification settings - Fork 2
Open
Labels
new validatorImplementation of a new validator classImplementation of a new validator class
Milestone
Description
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 InvalidDecimalErrorAdditionally, 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 StringTooLongErrorMetadata
Metadata
Assignees
Labels
new validatorImplementation of a new validator classImplementation of a new validator class