Email Validation from WTForm using Flask

lost9123193 picture lost9123193 · Aug 15, 2014 · Viewed 34.9k times · Source

I'm following a Flask tutorial from http://code.tutsplus.com/tutorials/intro-to-flask-adding-a-contact-page--net-28982 and am currently stuck on the validation step:

The old version had the following:

from flask.ext.wtf import Form, TextField, TextAreaField, SubmitField, validators, ValidationError

class ContactForm(Form):
name = TextField("Name",  [validators.Required("Please enter your name.")])
email = TextField("Email",  [validators.Required("Please enter your email address."), validators.Email("Please enter your email address.")])
submit = SubmitField("Send")

Reading the comments I updated it to this: (replaced validators.Required with InputRequired)

(same fields)  

class ContactForm(Form):  
name = TextField("Name", validators=[InputRequired('Please enter your name.')])
email = EmailField("Email",  validators=[InputRequired("Please enter your email address.")]), validators.Email("Please enter your email address.")])
submit = SubmitField("Send")

My only issue is I don't know what to do with the validators.Email. The error message I get is:

NameError: name 'validators' is not defined

I've looked over the documentation, perhaps I didn't delve deep enough but I can't seem to find an example for email validation.

Answer

Mehdi Sadeghi picture Mehdi Sadeghi · Aug 16, 2014

Try this:

from flask.ext.wtf import Form
from wtforms import validators
from wtforms.fields.html5 import EmailField

class ContactForm(Form):
    email = EmailField('Email address', [validators.DataRequired(), validators.Email()])