Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python flask app validate text field - allow no space

I have an application in Python Flask, where a username field has a validation on length. I would also like to prevent spaces within the username. How could I achieve that?

class RegistrationForm(Form):
    username = TextField('Username', [validators.Length(min=4, max=25)])
    email = TextField('Email Address', [validators.Email(message='Invalid email address.')])
like image 811
webminal.org Avatar asked Jun 09 '12 15:06

webminal.org


People also ask

How do you validate input in python Flask?

to validate the data, call the validate() method, which will return True if the data validates, False otherwise.

What is form Validate_on_submit?

The validate_on_submit() method of the form returns True when the form was submitted and the data was accepted by all the field validators. In all other cases, validate_on_submit() returns False . The return value of this method effectively serves to determine whether the form needs to be rendered or processed.

What is WTForms Flask?

Flask WTForms is a library that makes form handling easy and structured. It also ensures the effective handling of form rendering, validation, and security. To build forms with this approach, you start by creating a new file in our app directory and name it forms.py. This file will contain all the application forms.

How do you make a field in a Flask required?

Instead, pass required=True , which will set a bare attribute on the tag. Check the flags on a field to see if a Required validator was set: field. flags. required is a boolean.


1 Answers

You should be able to ensure that using the Regexp validator. I use the regex Django uses for the username form:

username = TextField('Username', [validators.Regexp(r'^[\w.@+-]+$'), validators.Length(min=4, max=25)])

This allows alphanumeric characters, dots, @, + and -. You can of course just use \w for alphanumeric characters.

like image 122
jeverling Avatar answered Sep 20 '22 08:09

jeverling