API Documentation

Validator Classes

class Validator

A validator class. Can have many fields attached to it to perform validation on data.

class Meta

A meta class to specify options for the validator. Uses the following fields:

messages = {}

only = []

exclues = []

clean(data)

Clean the data dictionary and return the cleaned values.

Parameters

data – Dictionary of data for all fields.

Returns

Dictionary of “clean” values.

Return type

dict

clean_fields(data)

For each field, check to see if there is a clean_<name> method. If so, run that method and set the returned value on the self.data dict. This happens after all validations so that each field can act on the cleaned data of other fields if needed.

Parameters

data – Dictionary of data to clean.

Returns

None

initialize_fields()

The dict self.base_fields is a model instance at this point. Turn it into an instance attribute on this meta class. Also intitialize any other special fields if needed in sub-classes.

Returns

None

validate(data=None, only=None, exclude=None)

Validate the data for all fields and return whether the validation was successful. This method also retains the validated data in self.data so that it can be accessed later.

This is usually the method you want to call after creating the validator instance.

Parameters
  • data – Dictionary of data to validate.

  • only – List or tuple of fields to validate.

  • exclude – List or tuple of fields to exclude from validation.

Returns

True if validation was successful. Otherwise False.

class ModelValidator(instance)

A validator class based on a Peewee model instance. Fields are automatically added based on the model instance, but can be customized.

Parameters

instance – Peewee model instance to use for data lookups and field generation.

convert_field(name, field)

Convert a single field from a Peewee model field to a validator field.

Parameters
  • name – Name of the field as defined on this validator.

  • name – Peewee field instance.

Returns

Validator field.

initialize_fields()

Convert all model fields to validator fields. Then call the parent so that overwrites can happen if necessary for manually defined fields.

Returns

None

perform_index_validation(data)

Validate any unique indexes specified on the model. This should happen after all the normal fields have been validated. This can add error messages to multiple fields.

Returns

None

save(force_insert=False)

Save the model and any related many-to-many fields.

Parameters

force_insert – Should the save force an insert?

Returns

Number of rows impacted, or False.

validate(data=None, only=None, exclude=None)

Validate the data for all fields and return whether the validation was successful. This method also retains the validated data in self.data so that it can be accessed later.

If data for a field is not provided in data then this validator will check against the provided model instance.

This is usually the method you want to call after creating the validator instance.

Parameters
  • data – Dictionary of data to validate.

  • only – List or tuple of fields to validate.

  • exclude – List or tuple of fields to exclude from validation.

Returns

True if validation is successful, otherwise False.

Fields

class Field(required=False, default=None, validators=None)

Base class from which all other fields should be derived.

Parameters
  • default – Is this field required?

  • default – Default value to be used if no incoming value is provided.

  • validators – List of validator functions to run.

class StringField(required=False, max_length=None, min_length=None, default=None, validators=None)

A field that will try to coerce value to a string.

Parameters
  • required – Is this field required?

  • default – Default value to be used if no incoming value is provided.

  • validators – List of validator functions to run.

  • max_length – Maximum length that should be enfocred.

  • min_length – Minimum length that should be enfocred.

class FloatField(required=False, low=None, high=None, default=None, validators=None)

A field that will try to coerce value to a float.

Parameters
  • required – Is this field required?

  • default – Default value to be used if no incoming value is provided.

  • validators – List of validator functions to run.

  • low – Lowest value that should be enfocred.

  • high – Highest value that should be enfocred.

class IntegerField(required=False, low=None, high=None, default=None, validators=None)

A field that will try to coerce value to an integer.

Parameters
  • required – Is this field required?

  • default – Default value to be used if no incoming value is provided.

  • validators – List of validator functions to run.

  • low – Lowest value that should be enfocred.

  • high – Highest value that should be enfocred.

class DecimalField(required=False, low=None, high=None, default=None, validators=None)

A field that will try to coerce value to a decimal.

Parameters
  • required – Is this field required?

  • default – Default value to be used if no incoming value is provided.

  • validators – List of validator functions to run.

  • low – Lowest value that should be enfocred.

  • high – Highest value that should be enfocred.

class DateField(required=False, low=None, high=None, default=None, validators=None)

A field that will try to coerce value to a date. Can accept a date object, string, or anything else that can be converted by dateutil.parser.parse.

Parameters
  • required – Is this field required?

  • default – Default value to be used if no incoming value is provided.

  • validators – List of validator functions to run.

  • low – Lowest value that should be enfocred.

  • high – Highest value that should be enfocred.

class TimeField(required=False, low=None, high=None, default=None, validators=None)

A field that will try to coerce value to a time. Can accept a time object, string, or anything else that can be converted by dateutil.parser.parse.

Parameters
  • required – Is this field required?

  • default – Default value to be used if no incoming value is provided.

  • validators – List of validator functions to run.

  • low – Lowest value that should be enfocred.

  • high – Highest value that should be enfocred.

class DateTimeField(required=False, low=None, high=None, default=None, validators=None)

A field that will try to coerce value to a datetime. Can accept a datetime object, string, or anything else that can be converted by dateutil.parser.parse.

Parameters
  • required – Is this field required?

  • default – Default value to be used if no incoming value is provided.

  • validators – List of validator functions to run.

  • low – Lowest value that should be enfocred.

  • high – Highest value that should be enfocred.

class BooleanField(required=False, default=None, validators=None)

A field that will try to coerce value to a boolean. By default the values is converted to string first, then compared to these values: values which are considered False: (‘0’, ‘{}’, ‘none’, ‘false’) And everything else is True.

class ModelChoiceField(query, lookup_field, required=False, **kwargs)

A field that allows for a single value based on a model query and lookup field.

Parameters
  • query – Query to use for lookup.

  • lookup_field – Field that will be queried for the value.

class ManyModelChoiceField(query, lookup_field, required=False, **kwargs)

A field that allows for multiple values based on a model query and lookup field.

Parameters
  • query – Query to use for lookup.

  • lookup_field – Field that will be queried for the value.

Field Validators

This module includes some basic validators, but it’s pretty easy to write your own if needed.

All validators return a function that can be used to validate a field. For example:

validator = peewee_validates.validate_required()

# Raises ValidationError since no data was provided for this field.
field = StringField()
validator(field, {})

# Does not raise any error since default data was provided.
field = StringField(default='something')
validator(field, {})
validate_email()

Validate the field is a valid email address.

Raises

ValidationError('email')

validate_equal(value)

Validate the field value is equal to the given value. Should work with anything that supports ‘==’ operator.

Parameters

value – Value to compare.

Raises

ValidationError('equal')

validate_function(method, **kwargs)

Validate the field matches the result of calling the given method. Example:

def myfunc(value, name):
    return value == name

validator = validate_function(myfunc, name='tim')

Essentially creates a validator that only accepts the name ‘tim’.

Parameters
  • method – Method to call.

  • kwargs – Additional keyword arguments passed to the method.

Raises

ValidationError('function')

validate_length(low=None, high=None, equal=None)

Validate the length of a field with either low, high, or equal. Should work with anything that supports len().

Parameters
  • low – Smallest length required.

  • high – Longest length required.

  • equal – Exact length required.

Raises

ValidationError('length_low')

Raises

ValidationError('length_high')

Raises

ValidationError('length_between')

Raises

ValidationError('length_equal')

validate_matches(other)

Validate the field value is equal to another field in the data. Should work with anything that supports ‘==’ operator.

Parameters

value – Field key to compare.

Raises

ValidationError('matches')

validate_model_unique(lookup_field, queryset, pk_field=None, pk_value=None)

Validate the field is a unique, given a queryset and lookup_field. Example:

validator = validate_model_unique(User.email, User.select())

Creates a validator that can validate the uniqueness of an email address.

Parameters
  • lookup_field – Peewee model field that should be used for checking existing values.

  • queryset – Queryset to use for lookup.

  • pk_field – Field instance to use when excluding existing instance.

  • pk_value – Field value to use when excluding existing instance.

Raises

ValidationError('unique')

validate_none_of(values)

Validate that a field is not in one of the given values.

Parameters

values – Iterable of invalid values.

Raises

ValidationError('none_of')

validate_not_empty()

Validate that a field is not empty (blank string).

Raises

ValidationError('empty')

validate_one_of(values)

Validate that a field is in one of the given values.

Parameters

values – Iterable of valid values.

Raises

ValidationError('one_of')

validate_range(low=None, high=None)

Validate the range of a field with either low, high, or equal. Should work with anything that supports ‘>’ and ‘<’ operators.

Parameters
  • low – Smallest value required.

  • high – Longest value required.

Raises

ValidationError('range_low')

Raises

ValidationError('range_high')

Raises

ValidationError('range_between')

validate_regexp(pattern, flags=0)

Validate the field matches the given regular expression. Should work with anything that supports ‘==’ operator.

Parameters
  • pattern – Regular expresion to match. String or regular expression instance.

  • pattern – Flags for the regular expression.

Raises

ValidationError('equal')

validate_required()

Validate that a field is present in the data.

Raises

ValidationError('required')