mpn
mpn

Reputation: 1018

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.

Upvotes: 19

Views: 21215

Answers (3)

Hendrik
Hendrik

Reputation: 463

@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.

Upvotes: 0

Emmet Gibney
Emmet Gibney

Reputation: 143

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/

Upvotes: 2

mpn
mpn

Reputation: 1018

Replacing the regex with

'^\w+$'

solved the problem.

Upvotes: 26

Related Questions