Home > Software engineering >  python validation ban special characters using flask
python validation ban special characters using flask

Time:04-12

I am trying to prevent user input from including special characters and am wondering the best way to do this. The question is as follows:

Create another custom validator that stops the user adding special characters (!@"'£$/, etc.) to their username.

from flask import Flask, render_template
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired, Length, ValidationError

app = Flask(__name__)
app.config['SECRET_KEY']='SOME_KEY'

class UserCheck:
    def __init__(self, banned, message=None):
        self.banned = banned
        if not message:
            message = 'Please choose another username'
        self.message = message

    def __call__(self, form, field):
        if field.data.lower() in (word.lower() for word in self.banned):
            raise ValidationError(self.message)

class myForm(FlaskForm):
    username = StringField('Username', validators=[
        DataRequired(),
        UserCheck(message="That username is not allowed", banned = ['root','admin','sys']),
        Length(min=2,max=15)
        ])
    submit = SubmitField('Sign up')

@app.route('/', methods=['GET','POST'])
def postName():
    form = myForm()
    if form.validate_on_submit():
        username = form.username.data
        return render_template('home.html', form = form, username=username)
    else:
        return render_template('home.html', form = form, username="")

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')

Many thanks

CodePudding user response:

In the UserCheck class you can also create a function that checks if the invalid characters are present in the username string using the regex module from the python standard library.

import re

def check_username(username):
    regex = re.compile('[@_!#$%^&*()<>?/\|}{~:]')

    if(regex.search(username) == None):
        print("username verified")
    else:
        print("illegal characters in username.")

CodePudding user response:

Follow up to Ian's answer. It took me about an hour to figure it out, but it wasn't as straight forward as what he posted.

Add import re

Modify UserCheck in the form.

class RegistrationForm(FlaskForm):
    username = StringField('Username', validators=[
        DataRequired(),
        UserCheck(message="Username or special characters not allowed",
                  banned=['root', 'admin', 'sys', 'administrator'],
                  regex="^(?=.*[- _!@#$%^&*., ?])"),
        Length(min=2, max=20)
    ])

Modify the class UserCheck

class UserCheck:
    def __init__(self, banned, regex, message=None):
        self.banned = banned
        self.regex = regex

        if not message:
            message = 'Please choose another username'
        self.message = message

    def __call__(self, form, field):
        p = re.compile(self.regex)
        if field.data.lower() in (word.lower() for word in self.banned):
            raise ValidationError(self.message)
        if re.search(p, field.data.lower()):
            raise ValidationError(self.message)
  • Related