编写WTForms表单的验证器,以比较两个字段的输入

时间:2019-06-09 18:44:31

标签: python flask-wtforms wtforms

我想有一个验证器,当ValidationException的输入小于feature_count的输入时,该验证器将触发effective_rank

我在该网站(http://flask.pocoo.org/snippets/64/)上找到了有关wtforms验证程序的信息,但不知道如何将其应用于我的问题。

你能告诉我如何做吗?

这是我的代码:

from flask_wtf import FlaskForm
from wtforms import SubmitField, IntegerField, ValidationError
from wtforms.validators import DataRequired, NumberRange, EqualTo,


class RequestDataForm(FlaskForm):
feature_count = IntegerField('Number of features', validators=[DataRequired(), NumberRange(min=1, max=50)])

effective_rank = IntegerField('Effective Rank', validators=[DataRequired()])

noise = IntegerField('Noise', validators=[DataRequired(), NumberRange(min=0, max=1)])

submit = SubmitField('Submit')

1 个答案:

答案 0 :(得分:1)

有一个名为Validator的{​​{1}},可用于比较两个字段的相等性。如果您希望EqualTofeature_count相同,则只需添加:

effective_rank

但是,在您的特定情况下,您要确保feature_count = IntegerField('Number of features', validators=[DataRequired(), EqualTo('effective_rank'), NumberRange(min=1, max=50)]) ,所以我最好的解决方案是复制并粘贴LessThan类的代码,针对您的特定情况将其重命名,更改比较并将其重新用作自定义类:

EqualTo

然后您可以使用:

class EqualTo(object):  # --> Change to 'LessThan'
    """
    Compares the values of two fields.

    :param fieldname:
        The name of the other field to compare to.
    :param message:
        Error message to raise in case of a validation error. Can be
        interpolated with `%(other_label)s` and `%(other_name)s` to provide a
        more helpful error.
    """
    def __init__(self, fieldname, message=None):
        self.fieldname = fieldname
        self.message = message

    def __call__(self, form, field):
        try:
            other = form[self.fieldname]
        except KeyError:
            raise ValidationError(field.gettext("Invalid field name '%s'.") % self.fieldname)
        if field.data != other.data:  #  --> Change to >= from !=
            d = {
                'other_label': hasattr(other, 'label') and other.label.text or self.fieldname,
                'other_name': self.fieldname
            }
            message = self.message
            if message is None:
                message = field.gettext('Field must be equal to %(other_name)s.')

            raise ValidationError(message % d)