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')
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()])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With