20

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

2 Answers 2

22

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
from wtforms import ValidationError

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

    def validate_match1(self, 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)
Sign up to request clarification or add additional context in comments.

2 Comments

@janmpeterka Should be def validate_match1(self, form, field) or you can make the method static with @staticmethod
Also from wtforms import ValidationError seems to be missed. Please consider editing this answer.
5
from flask_wtf import FlaskForm
from wtforms import StringField, validators

# Define a custom validator function
def custom_validator(form, field):
    if len(field.data) < 5:
        raise validators.ValidationError('Input must be at least 5 characters long')

# Define a Flask form with a StringField and a custom validator
class MyForm(FlaskForm):
    my_field = StringField('My Field', validators=[validators.InputRequired(), custom_validator])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.