Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom validators in WTForms using Flask

I need to make a custom validator in WTForms where the input is to be: number:number - e.g. 2:1

match1 = StringField('Russia-Saudi Arabia', validators=[DataRequired()])

So, my question is - how to create such validator?

I've looked upon the documentation at http://wtforms.readthedocs.io/en/latest/validators.html, but was not very helpful (for me) in this case.

Thanks in advance

like image 362
Jacob Singh Risgaard Knudsen Avatar asked May 14 '18 09:05

Jacob Singh Risgaard Knudsen


People also ask

How do I import a validator into a flask?

We can use the Length() validator with min parameter: # ... from wtforms. validators import ValidationError, DataRequired, Length class GreetUserForm(FlaskForm): username = StringField(label=('Enter Your Name:'), validators=[DataRequired(), Length(min=5)]) submit = SubmitField(label=('Submit')) # ...

Which of the following validators can be used to compare values of two form fields?

You can perform this type of form validation by using the CompareValidator control. To compare two dates, you need to set the ControlToValidate, ControlToCompare, Operator, and Type properties of the CompareValidator control.

What are custom validators?

Building a custom validator In it's simplest form, a validator is really just a function that takes a Control and returns either null when it's valid, or and error object if it's not.


1 Answers

You can write a custom validator within a form by writing a validate_{field_name} method. If it raises a ValidationError, the form will not be valid and will display the error.

For your specific case, here's a solution using regex. It finds the match for the string, and then uses a bit of splitting to get back the scores. After validating the form you can access the scores by form.score1, form.score2.

import re
from flask_wtf import FlaskForm

class MatchForm(FlaskForm):
    match1 = StringField("Russia-Saudi Arabia", validators=[DataRequired()])

    def validate_match1(form, field):
        if not re.search(r"^[0-9]+:[0-9]+$", field.data):
            raise ValidationError("Invalid input syntax")

        s1, s2 = form.data.split(":")
        form.score1 = int(s1)
        form.score2 = int(s2)
like image 155
Joost Avatar answered Sep 18 '22 15:09

Joost