简体   繁体   中英

Regex validation with WTForms and python

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.

Replacing the regex with

'^\w+$'

solved the problem.

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/

@mpn solution works fine but I was wondering why \\w+ is not matching the whole string.

In wtforms' Regexp class whitin the method __call__ you will see that self.regex.match(field.data or '') will be called. The documentation of re.py states about re.match that:

If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding match object.

Hence, we will have to use ^ to match the start of the string and $ to match the end of the string. Read more about the special characters in the documentation .

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