[英]Non required email validation in Flask WTForms
I am using wtforms with flask and I have an input box for the email.我正在使用带有烧瓶的wtforms ,并且我有一个电子邮件输入框。 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.
用户可以省略它,但如果他们输入它,我想确保它通过 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 .我想使用 Flask-WTforms 实现这一点的唯一可能方法是创建一个自定义验证器。 In that case, is there a way to utilize the Email() validator in my custom validator, so I won't have to reimplement it ?
在这种情况下,有没有办法在我的自定义验证器中使用 Email() 验证器,这样我就不必重新实现它?
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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.