Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 769
mpn Avatar asked Aug 27 '14 17:08

mpn


People also ask

What is WTForms in Python?

WTForms is a Python library that provides flexible web form rendering. You can use it to render text fields, text areas, password fields, radio buttons, and others. WTForms also provides powerful data validation using different validators, which validate that the data the user submits meets certain criteria you define.

Is RegEx input validation?

Regular expressions describe patterns that match combinations of characters in strings. They have a variety of applications, such as validating user input from HTML forms. You can use regex to validate with JavaScript or via the HTML pattern attribute.

What is RegEx in validation?

RegEx validation is essentially a syntax check which makes it possible to see whether an email address is spelled correctly, has no spaces, commas, and all the @s, dots and domain extensions are in the right place.


2 Answers

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/

like image 36
Emmet Gibney Avatar answered Sep 23 '22 17:09

Emmet Gibney


Replacing the regex with

'^\w+$'

solved the problem.

like image 99
mpn Avatar answered Sep 21 '22 17:09

mpn