Validator¶
-
class
valedictory.
Validator
(fields=None, allow_unknown_fields=None, error_messages=None, **kwargs)[source]¶ The base class from which all custom validators are created. To define a resuable custom validator, create a new subclass of
Validator
and add any fields required:from valedictory import Validator, fields class ContactValidator(Validator): allow_unknown_fields = True default_error_messages = { 'unknown': "I don't know what this field is" } name = fields.CharField() height = fields.IntegerField() date_of_birth = fields.DateField() contact_validator = ContactValidator()
Alternatively, a validator can be defined by instantiating
Validator
:contact_validator = Validator( allow_unknown_fields = True, error_messages = { 'unknown': "I don't know what this field is" }, fields={ 'name': fields.CharField(), 'height': fields.IntegerField(), 'date_of_birth': fields.DateField() }, )
This is useful for one-off validators, or with a
NestedValidator
.Attributes
-
allow_unknown_fields
= False¶ Whether unknown fields in the data should be treated as an error, or ignored. If
allow_unknown_fields
isTrue
, fields in the data being cleaned that do not have a corresponding field on the class cause aInvalidDataException
to be thrownThe default is
False
, unknown fields are not allowed.
-
fields
= {name: Field()}¶ A dictionary of all the fields on this validator
-
default_error_messages
= {'error': "Error message"}¶ A dictionary of strings for each error message that can be thrown. You can override error messages by overriding this dictionary. Only the error messages being overridden need to be set, other error messages will be taken from the parent classes.
- unknown
- Thrown when an unknown key is present in the data being validated
and
allow_unknown_fields
isTrue
.
Methods
-
clean
(data, *args, **kwargs)¶ Take input data, validate that it conforms to the required schema, and return the cleaned output.
If the data does not conform to the required schema, an
InvalidDataException
will be raised.
-
error
(code, params=None, cls=<class 'valedictory.exceptions.ValidationException'>, **kwargs)¶ Construct a validation exception. The message will be pulled from the
default_error_messages
dictionary usingcode
as the key. If the error message takes format parameters, pass in a dict as theparams
argument.
-