简体   繁体   中英

Validators in wtforms Flask Python

I tried adding Number range to password in my registration page in order to make sure that there is at least one number in my password column, when I remove the Number range , it works fine , but if I add it again , it throws an error

from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField, BooleanField from wtforms.validators import DataRequired, length, Email, EqualTo, NumberRange

class RegistrationForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired(),
                            length(min=2, max=20)] )
    email = StringField('Email', validators=[DataRequired(),
                            Email(message="Please input a valid email address")])
    password = PasswordField('Password', validators=[DataRequired(),
                                length(min=5, max=12), NumberRange(min=1, max=3)])
    confirm_password = PasswordField('Confirm_Password',
                                    validators=[DataRequired(),
                                    EqualTo('password', message="Your password does not match")] )
    submit = SubmitField('SignUp')

class LoginForm(FlaskForm):
    email = StringField('Email', validators=[DataRequired(),
                            Email()])
    password = PasswordField('Password', validators=[DataRequired() ])
    remember = BooleanField('Remember me')

    submit = SubmitField('Login')

Here is the error when I try adding the Number range

TypeError
TypeError: must be real number, not str

The issue is that NumberRange() only accepts number types (integer, float, double, etc) but will always fail when passed a string. This is what your error message is telling you, "input must be a real number, not a string".

Solution: use Regexp()

Regexp() will allow you to compare the user's input against a regular expression. You can make this as complex as you would like but to solve your current requirements of "at least one digit" the following should work: Regexp('/d')

Last note. I noticed you were using DataRequired() , WTForms documentation recommends using InputRequired() instead, unless in specific use-cases which I don't see applying here.

References: https://wtforms.readthedocs.io/en/2.3.x/validators/

我遇到了这个问题,我将 NumberRange 更改为 Length .. 并且它起作用了'

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