Regex validation with WTForms and python

廉价感情. 提交于 2019-12-06 19:44:24

问题


Here is my code:

class CreateUser(Form):
    username = StringField('Username', [
        validators.Regexp('\w+', message="Username must contain only letters numbers or underscore"),
        validators.Length(min=5, max=25, message="Username must be betwen 5 & 25 characters")

    ])

    password = PasswordField('New Password', [
        validators.DataRequired(), 
        validators.EqualTo('confirm', message='Passwords must match')
    ])

    confirm  = PasswordField('Repeat Password')

So the problem exists at line 3. I want the username to be only alpha numeric characters. For some reason this regex is only checking the first character. Is there a reason why the + symbol is not working here? Thanks.


回答1:


Replacing the regex with

'^\w+$'

solved the problem.




回答2:


I know this was answered a long time ago, but another option I discovered to provide alphanumeric validation on WTForms is AlphaNumeric()

from wtforms_validators import AlphaNumeric
...

class SignupForm(Form):
    login_id = StringField('login Id', [DataRequired(), AlphaNumeric()])

More details here https://pypi.org/project/wtforms-validators/



来源:https://stackoverflow.com/questions/25533370/regex-validation-with-wtforms-and-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!