Mustafa
Mustafa

Reputation: 9

Flask-Wtf Regex and Length Validation don't working

class checkUserName(FlaskForm):
    username = StringField('Username',[Length(min=5, max=20),Regexp('[0-9A-Za-z_]+'),DataRequired('Required')])

I want to accept username only combination between number, character, and underscore like admin and reject username like ''''''''''' with minimum length 5 and maximum length 20, but the validation didn't work, how can I fix it?

Upvotes: 0

Views: 2469

Answers (3)

BRENDA MWANGI
BRENDA MWANGI

Reputation: 11

I was getting this following error:

NameError: name 'Regexp' is not defined

And this is how I solved it:

from wtforms.validators import Regexp

Upvotes: 0

Naved Shaikh
Naved Shaikh

Reputation: 89

You can use:

from wtforms.validators import Length

Upvotes: -1

dhentris
dhentris

Reputation: 198

Try change your code like this:

username = StringField('Username', validators=[Length(min=5, max=20),Regexp('[0-9A-Za-z_]+'),DataRequired('Required')])

or like this :

username = StringField('Username', [validators.Length(min=5, max=20), validators.Regexp('[0-9A-Za-z_]+'), validators.DataRequired('Required')])

if you want ''''''''''' accept as username you can change the regex like this:

("[0-9A-Za-z_']+")

that's mean you accept a set of character in square bracket and + mean the character ahead repeat by one or more time.

if you want to accept only admin, admin'''' you can try this:

`("[0-9A-Za-z_]+'*")`
  1. [0-9A-Za-z_]+ : accept a set of character in square bracket with one ore more repetition
  2. '* : accept ' character after the character above with 0 or more repetition.

Upvotes: 0

Related Questions