Reputation: 2694
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')
Upvotes: 4
Views: 1562
Reputation: 1
A complete email validation form (login form)
from flask import Flask, render_template
from flask_wtf import FlaskForm
from wtforms import StringField,PasswordField,SubmitField
from wtforms.validators import DataRequired , Email , Length
class login_form(FlaskForm):
email = StringField(label='Email *',validators=[DataRequired(),Email(message="Invalid Id , Check the Format")] ) #Email() can also be included
password = PasswordField(label='Password *',validators=[Length(min=6 ) ]) # message="Atleast 6 characters " can also be included
submit = SubmitField(label="Log In")
Upvotes: 0
Reputation: 106
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()])
Upvotes: 7