Validators

A validator simply takes an input, verifies it fulfills some criterion, such as a maximum length for a string and returns. Or, if the validation fails, raises a ValidationError. This system is very simple and flexible, and allows you to chain any number of validators on fields.

class wtforms.validators.ValidationError(message=u'', *args, **kwargs)
Raised when a validator fails to validate its input.
class wtforms.validators.StopValidation(message=u'', *args, **kwargs)

Causes the validation chain to stop.

If StopValidation is raised, no more validators in the validation chain are called. If raised with a message, the message will be added to the errors list.

Built-in validators

class wtforms.validators.Email(message=u'Invalid email address.')

Validates an email address. Note that this uses a very primitive regular expression and should only be used in instances where you later verify by other means, such as email activation or lookups.

Parameter:message – Error message to raise in case of a validation error.
class wtforms.validators.EqualTo(fieldname, message=None)

Compares the values of two fields.

Parameters:
  • fieldname – The name of the other field to compare to.
  • message – Error message to raise in case of a validation error.

This validator can be used to facilitate in one of the most common scenarios, the password change form:

class ChangePassword(Form):
    password = PasswordField('New Password', [Required(), EqualTo('confirm', mesage='Passwords must match')])
    confirm  = PasswordField('Repeat Password')

In the example, we use the Required validator to prevent the EqualTo validator from trying to see if the passwords do not match if there was no passwords specified at all. Because Required stops the validation chain, EqualTo is not run in the case the password field is left empty.

class wtforms.validators.IPAddress(message=u'Invalid IP address.')

Validates an IP(v4) address.

Parameter:message – Error message to raise in case of a validation error.
class wtforms.validators.Length(min=-1, max=-1, message=None)

Validates the length of a string.

Parameters:
  • min – The minimum required length of the string. If not provided, minimum length will not be checked.
  • max – The maximum length of the string. If not provided, maximum length will not be checked.
  • message – Error message to raise in case of a validation error. A default containing min and max length is provided.
class wtforms.validators.Optional
Allows empty input and stops the validation chain from continuing.
class wtforms.validators.Required(message=u'This field is required.')

Validates that the field contains data. This validator will stop the validation chain on error.

Parameter:message – Error message to raise in case of a validation error.
class wtforms.validators.Regexp(regex, flags=0, message=u'Invalid input.')

Validates the field against a user provided regexp.

Parameters:
  • regex – The regular expression string to use. Can also be a compiled regular expression pattern.
  • flags – The regexp flags to use, for example re.IGNORECASE. Ignored if regex is not a string.
  • message – Error message to raise in case of a validation error.
class wtforms.validators.URL(require_tld=True, message=u'Invalid URL.')

Simple regexp based url validation. Much like the email validator, you probably want to validate the url later by other means if the url must resolve.

Parameters:
  • require_tld – If true, then the domain-name portion of the URL must contain a .tld suffix. Set this to false if you want to allow domains like localhost.
  • message – Error message to raise in case of a validation error.

Custom validators

Defining your own validators is easy. You simply make a function that takes a list of configuration directives, and then returns a callable. The returned callable should take two positional arguments, which are a form instance and the field instance being validated. It is helpful to design your validators with a message argument to provide a way to override the error message.

Let’s look at a possible validator which checks if a file upload’s extension is that of an image:

def is_image(message=u'Images only!', extensions=None):
    if not extensions:
        extensions = ('jpg', 'jpeg', 'png', 'gif')
    def _is_image(form, field):
        if not field.data or field.data.split('.')[-1] not in extensions:
            raise ValidationError(message)
    return _is_image

And the way it’s used:

avatar = FileField(u'Avatar', [is_image(u'Only images are allowed.', extensions=['gif', 'png'])])

The outer function sets configuration directives, in this case the message and the extensions. The inner function provides the actual validation: If the field contains no data, or an un-approved extension, ValidationError with the message is raised. Otherwise we just the let function return normally.

You could also define the validator as a class:

class IsImage(object):
    def __init__(self, message=u'Images only!', extensions=None):
        self.message = message
        if not extensions:
            extensions = ('jpg', 'jpeg', 'png', 'gif')
        self.extensions = extensions

    def __call__(self, form, field):
        if not field.data or field.data.split('.')[-1] not in extensions:
            raise ValidationError(self.message)

Which option you choose is entirely down to preference.

Table Of Contents

Previous topic

Fields

Next topic

Widgets

This Page