Make username regex to stop the validation chain

with a decorator to replace ValidationError with StopValidation
This commit is contained in:
TheAMM 2017-06-19 14:50:00 +03:00
parent 94574d1682
commit 081eb16246
1 changed files with 14 additions and 2 deletions

View File

@ -5,11 +5,12 @@ from nyaa import bencode, utils, models
import os import os
import re import re
import functools
from flask_wtf import FlaskForm from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileRequired from flask_wtf.file import FileField, FileRequired
from wtforms import StringField, PasswordField, BooleanField, TextAreaField, SelectField,\ from wtforms import StringField, PasswordField, BooleanField, TextAreaField, SelectField,\
HiddenField HiddenField
from wtforms.validators import DataRequired, Optional, Email, Length, EqualTo, ValidationError from wtforms.validators import DataRequired, Optional, Email, Length, EqualTo, ValidationError, StopValidation
from wtforms.validators import Regexp from wtforms.validators import Regexp
# For DisabledSelectField # For DisabledSelectField
@ -37,6 +38,17 @@ class Unique(object):
raise ValidationError(self.message) raise ValidationError(self.message)
def stop_on_validation_error(f):
''' A decorator which will turn raised ValidationErrors into StopValidations '''
@functools.wraps(f)
def decorator(*args, **kwargs):
try:
return f(*args, **kwargs)
except ValidationError as e:
# Replace the error with a StopValidation to stop the validation chain
raise StopValidation(*e.args) from e
return decorator
_username_validator = Regexp( _username_validator = Regexp(
r'^[a-zA-Z0-9_\-]+$', r'^[a-zA-Z0-9_\-]+$',
message='Your username must only consist of alphanumerics and _- (a-zA-Z0-9_-)') message='Your username must only consist of alphanumerics and _- (a-zA-Z0-9_-)')
@ -51,7 +63,7 @@ class RegisterForm(FlaskForm):
username = StringField('Username', [ username = StringField('Username', [
DataRequired(), DataRequired(),
Length(min=3, max=32), Length(min=3, max=32),
_username_validator, stop_on_validation_error(_username_validator),
Unique(User, User.username, 'Username not availiable') Unique(User, User.username, 'Username not availiable')
]) ])