Regex validation with WTForms and python

mpn picture mpn · Aug 27, 2014 · Viewed 12k times · Source

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.

Answer

mpn picture mpn · Aug 27, 2014

Replacing the regex with

'^\w+$'

solved the problem.