From 66f2da31b6d1c860d9c065b2217186db9f2871d8 Mon Sep 17 00:00:00 2001 From: viveksantayana Date: Sat, 4 Dec 2021 15:41:24 +0000 Subject: [PATCH] Refactored form model for custom validators --- ref-test/admin/models/{forms.py => forms/__init__.py} | 10 ++++++++-- ref-test/admin/models/forms/validators.py | 11 +++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) rename ref-test/admin/models/{forms.py => forms/__init__.py} (95%) create mode 100644 ref-test/admin/models/forms/validators.py diff --git a/ref-test/admin/models/forms.py b/ref-test/admin/models/forms/__init__.py similarity index 95% rename from ref-test/admin/models/forms.py rename to ref-test/admin/models/forms/__init__.py index 9ca6e1e..5bf60a4 100644 --- a/ref-test/admin/models/forms.py +++ b/ref-test/admin/models/forms/__init__.py @@ -1,9 +1,11 @@ from flask_wtf import FlaskForm from flask_wtf.file import FileField, FileRequired, FileAllowed -from wtforms import StringField, PasswordField, BooleanField, DateField, SelectField +from wtforms import StringField, PasswordField, BooleanField, DateField, SelectField, IntegerField from wtforms.validators import InputRequired, Email, Length, EqualTo, Optional from datetime import date, timedelta +from .validators import value + class LoginForm(FlaskForm): username = StringField('Username', validators=[InputRequired(), Length(min=4, max=15)]) password = PasswordField('Password', validators=[InputRequired(), Length(min=6, max=30, message='The password must be between 6 and 20 characters long.')]) @@ -53,4 +55,8 @@ class CreateTest(FlaskForm): class UploadDataForm(FlaskForm): data_file = FileField('Data File', validators=[FileRequired(), FileAllowed(['json'])]) - default = BooleanField('Make Default', render_kw={'checked': True}) \ No newline at end of file + default = BooleanField('Make Default', render_kw={'checked': True}) + +class AddTimeAdjustment(FlaskForm): + time = IntegerField('Extra Time (Minutes)', validators=[InputRequired(), value(max=60)]) + \ No newline at end of file diff --git a/ref-test/admin/models/forms/validators.py b/ref-test/admin/models/forms/validators.py new file mode 100644 index 0000000..7caeb05 --- /dev/null +++ b/ref-test/admin/models/forms/validators.py @@ -0,0 +1,11 @@ +from wtforms.validators import ValidationError + +def value(min=0, max=None): + message = f'Value must be between {min} and {max}.' + + def _length(form, field): + value = field.data or 0 + if value < min or max != None and value > max: + raise ValidationError(message) + + return _length \ No newline at end of file