简体   繁体   中英

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

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()])
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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM