Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non required email validation in Flask WTForms

I am using wtforms with flask and I have an input box for the email. I want to validate the email entry but also have it as non-required field. The user can ommit it, but if they enter it I want to make sure it passes the Email validator of wtforms.

Ideally, I would like to have something like this:

email = StringField('Email', validators=[Email(), DataNotRequired()])

or

email = StringField('Email', validators=[Email(required=False)])

I guess the only possible way to achieve this using Flask-WTforms, is to create a custom validator. In that case, is there a way to utilize the Email() validator in my custom validator, so I won't have to reimplement it ?

Something like that:

def validate_email(form, field):
    if len(field.data) > 0:
        if (not Email(field.data)):
            raise ValidationError('Email is invalid')
like image 540
thanos.a Avatar asked Oct 19 '25 22:10

thanos.a


1 Answers

the validator "Optional" should solve the problem. "Optional" stops the evaluation chain if the data field contains no value or only whitespace, without raising an error:

email = StringField('Email', validators=[Optional(), Email()])
like image 75
joachum hue Avatar answered Oct 21 '25 11:10

joachum hue