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')