Custom validators in WTForms using Flask

这一生的挚爱 提交于 2019-12-01 16:24:20
Joost

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!