Table Of Contents
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=None)¶
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.
Parameters: 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. 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', [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=None)¶
Validates an IP(v4) address.
Parameters: 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. Can be interpolated using %(min)d and %(max)d if desired. Useful defaults are provided depending on the existence of min and max.
- class wtforms.validators.MacAddress(message=None)¶
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)¶
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.
- class wtforms.validators.Optional¶
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.
This also sets the optional flag on fields it is used on.
- class wtforms.validators.Required(message=None)¶
Validates that the field contains data. This validator will stop the validation chain on error.
If the data is empty, also removes prior errors (such as processing errors) from the field.
Parameters: message – Error message to raise in case of a validation error. This also sets the required flag on fields it is used on.
- class wtforms.validators.Regexp(regex, flags=0, message=None)¶
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=None)¶
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.
- class wtforms.validators.UUID(message=None)¶
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)¶
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)¶
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.
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 = TextField('Name', [Required()])
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 = TextField('Name', [Required(), 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 = TextField('Name', [Required(), 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 = u'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 to True 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):
field_flags = ('accepts_bbcode', )
pass # validator implementation here
# factory implementation
def valid_bbcode():
def _valid_bbcode(form, field):
pass # validator implementation here
_valid_bbcode.field_flags = ('accepts_bbcode', )
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:
- Flags can only set boolean values, and another validator cannot unset them.
- If multiple fields set the same flag, its value is still True.
- Flags are set from validators only in Field.__init__(), so inline validators and extra passed-in validators cannot set them.