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='', *args, **kwargs)[source]

Raised when a validator fails to validate its input.

class wtforms.validators.StopValidation(message='', *args, **kwargs)[source]

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.DataRequired(message=None)[source]

Checks the field’s data is ‘truthy’ otherwise stops the validation chain.

This validator checks that the data attribute on the field is a ‘true’ value (effectively, it does if field.data.) Furthermore, if the data is a string type, a string containing only whitespace characters is considered false.

If the data is empty, also removes prior errors (such as processing errors) from the field.

NOTE this validator used to be called Required but the way it behaved (requiring coerced data, not input data) meant it functioned in a way which was not symmetric to the Optional validator and furthermore caused confusion with certain fields which coerced data to ‘falsey’ values like 0, Decimal(0), time(0) etc. Unless a very specific reason exists, we recommend using the InputRequired instead.

Parameters:

message – Error message to raise in case of a validation error.

Sets the required attribute on widgets.

This also sets the required flag on fields it is used on. This flag causes the required attribute to be rendered in the tag, which prevents a request/response cycle for validation. This behavior can be overridden in the following ways:

  • Specifying required=False when rendering in the template.

  • Making a custom a widget that doesn’t set it.

  • Rendering the novalidate attribute” on the form tag, or the formnovalidate attribute on a submit button.

The required flag behavior also applies to the InputRequired class.

class wtforms.validators.Email(message=None, granular_message=False, check_deliverability=False, allow_smtputf8=True, allow_empty_local=False)[source]

Validates an email address. Requires email_validator package to be installed. For ex: pip install wtforms[email].

Parameters:
  • message – Error message to raise in case of a validation error.

  • granular_message – Use validation failed message from email_validator library (Default False).

  • check_deliverability – Perform domain name resolution check (Default False).

  • allow_smtputf8 – Fail validation for addresses that would require SMTPUTF8 (Default True).

  • allow_empty_local – Allow an empty local part (i.e. @example.com), e.g. for validating Postfix aliases (Default False).

class wtforms.validators.EqualTo(fieldname, message=None)[source]

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. Can be interpolated with %(other_label)s and %(other_name)s to provide a more helpful 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', [InputRequired(), EqualTo('confirm', message='Passwords must match')])
    confirm  = PasswordField('Repeat Password')

In the example, we use the InputRequired 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 InputRequired stops the validation chain, EqualTo is not run in the case the password field is left empty.

class wtforms.validators.InputRequired(message=None)[source]

Validates that input was provided for this field.

Note there is a distinction between this and DataRequired in that InputRequired looks that form-input data was provided, and DataRequired looks at the post-coercion data. This means that this validator only checks whether non-empty data was sent, not whether non-empty data was coerced from that data. Initially populated data is not considered sent.

Sets the required attribute on widgets.

This also sets the required flag on fields it is used on. See DataRequired for a description of behavior regarding this flag.

class wtforms.validators.IPAddress(ipv4=True, ipv6=False, message=None)[source]

Validates an IP address.

Parameters:
  • ipv4 – If True, accept IPv4 addresses as valid (default True)

  • ipv6 – If True, accept IPv6 addresses as valid (default False)

  • message – Error message to raise in case of a validation error.

class wtforms.validators.Length(min=-1, max=-1, message=None)[source]

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. Can be interpolated using %(min)d and %(max)d if desired. Useful defaults are provided depending on the existence of min and max.

When supported, sets the minlength and maxlength attributes on widgets.

class wtforms.validators.MacAddress(message=None)[source]

Validates a MAC address.

Parameters:

message – Error message to raise in case of a validation error.

class wtforms.validators.NumberRange(min=None, max=None, message=None)[source]

Validates that a number is of a minimum and/or maximum value, inclusive. This will work with any comparable number type, such as floats and decimals, not just integers.

Parameters:
  • min – The minimum required value of the number. If not provided, minimum value will not be checked.

  • max – The maximum value of the number. If not provided, maximum value will not be checked.

  • message – Error message to raise in case of a validation error. Can be interpolated using %(min)s and %(max)s if desired. Useful defaults are provided depending on the existence of min and max.

When supported, sets the min and max attributes on widgets.

class wtforms.validators.Optional(strip_whitespace=True)[source]

Allows empty input and stops the validation chain from continuing.

If input is empty, also removes prior errors (such as processing errors) from the field.

Parameters:

strip_whitespace – If True (the default) also stop the validation chain on input which consists of only whitespace.

Sets the optional attribute on widgets.

This also sets the optional flag on fields it is used on.

class wtforms.validators.Regexp(regex, flags=0, message=None)[source]

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, allow_ip=True, message=None)[source]

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.

  • allow_ip – If false, then give ip as host will fail validation

  • message – Error message to raise in case of a validation error.

class wtforms.validators.UUID(message=None)[source]

Validates a UUID.

Parameters:

message – Error message to raise in case of a validation error.

class wtforms.validators.AnyOf(values, message=None, values_formatter=None)[source]

Compares the incoming data to a sequence of valid inputs.

Parameters:
  • values – A sequence of valid inputs.

  • message – Error message to raise in case of a validation error. %(values)s contains the list of values.

  • values_formatter – Function used to format the list of values in the error message.

class wtforms.validators.NoneOf(values, message=None, values_formatter=None)[source]

Compares the incoming data to a sequence of invalid inputs.

Parameters:
  • values – A sequence of invalid inputs.

  • message – Error message to raise in case of a validation error. %(values)s contains the list of values.

  • values_formatter – Function used to format the list of values in the error message.

class wtforms.validators.ReadOnly[source]

Set a field readonly.

Validation fails if the form data is different than the field object data, or if unset, from the field default data.

class wtforms.validators.Disabled[source]

Set a field disabled.

Validation fails if the form data has any value.

Custom validators

We will step through the evolution of writing a length-checking validator similar to the built-in Length validator, starting from a case-specific one to a generic reusable validator.

Let’s start with a simple form with a name field and its validation:

class MyForm(Form):
    name = StringField('Name', [InputRequired()])

    def validate_name(form, field):
        if len(field.data) > 50:
            raise ValidationError('Name must be less than 50 characters')

Above, we show the use of an in-line validator to do validation of a single field. In-line validators are good for validating special cases, but are not easily reusable. If, in the example above, the name field were to be split into two fields for first name and surname, you would have to duplicate your work to check two lengths.

So let’s start on the process of splitting the validator out for re-use:

def my_length_check(form, field):
    if len(field.data) > 50:
        raise ValidationError('Field must be less than 50 characters')

class MyForm(Form):
    name = StringField('Name', [InputRequired(), my_length_check])

All we’ve done here is move the exact same code out of the class and as a function. Since a validator can be any callable which accepts the two positional arguments form and field, this is perfectly fine, but the validator is very special-cased.

Instead, we can turn our validator into a more powerful one by making it a factory which returns a callable:

def length(min=-1, max=-1):
    message = 'Must be between %d and %d characters long.' % (min, max)

    def _length(form, field):
        l = field.data and len(field.data) or 0
        if l < min or max != -1 and l > max:
            raise ValidationError(message)

    return _length

class MyForm(Form):
    name = StringField('Name', [InputRequired(), length(max=50)])

Now we have a configurable length-checking validator that handles both minimum and maximum lengths. When length(max=50) is passed in your validators list, it returns the enclosed _length function as a closure, which is used in the field’s validation chain.

This is now an acceptable validator, but we recommend that for reusability, you use the pattern of allowing the error message to be customized via passing a message= parameter:

class Length(object):
    def __init__(self, min=-1, max=-1, message=None):
        self.min = min
        self.max = max
        if not message:
            message = 'Field must be between %i and %i characters long.' % (min, max)
        self.message = message

    def __call__(self, form, field):
        l = field.data and len(field.data) or 0
        if l < self.min or self.max != -1 and l > self.max:
            raise ValidationError(self.message)

length = Length

In addition to allowing the error message to be customized, we’ve now converted the length validator to a class. This wasn’t necessary, but we did this to illustrate how one would do so. Because fields will accept any callable as a validator, callable classes are just as applicable. For complex validators, or using inheritance, you may prefer this.

We aliased the Length class back to the original length name in the above example. This allows you to keep API compatibility as you move your validators from factories to classes, and thus we recommend this for those writing validators they will share.

Setting flags on the field with validators

Sometimes, it’s useful to know if a validator is present on a given field, like for use in template code. To do this, validators are allowed to specify flags which will then be available on the field's flags object. Some of the built-in validators such as Required already do this.

To specify flags on your validator, set the field_flags attribute on your validator. When the Field is constructed, the flags with the same name will be set on your field. For example, let’s imagine a validator that validates that input is valid BBCode. We can set a flag on the field then to signify that the field accepts BBCode:

# class implementation
class ValidBBCode(object):
    def __init__(self):
        self.field_flags = {'accepts_bbcode': True}

# factory implementation
def valid_bbcode():
    def _valid_bbcode(form, field):
        pass # validator implementation here

    _valid_bbcode.field_flags = {'accepts_bbcode': True}
    return _valid_bbcode

Then we can check it in our template, so we can then place a note to the user:

{{ field(rows=7, cols=70) }}
{% if field.flags.accepts_bbcode %}
    <div class="note">This field accepts BBCode formatting as input.</div>
{% endif %}

Some considerations on using flags:

  • Boolean flags will set HTML valueless attributes (e.g. {required: True} will give <input type=”text” required>). Other flag types will set regular HTML attributes (e.g. {maxlength: 8} will give <input type=”text” maxlength=”8”>).

  • If multiple validators set the same flag, the flag will have the value set by the first validator.

  • Flags are set from validators only in Field.__init__(), so inline validators and extra passed-in validators cannot set them.