WTForms内联验证超过1个字段

时间:2016-01-15 15:41:32

标签: python flask wtforms flask-wtforms

我正在使用WTForms验证,我想对两个字段执行操作,然后返回一条错误消息。

我知道我可以这样做:

class SignupForm(Form):
    age = IntegerField(u'Age')

    def validate_age(form, field):
        if field.data < 13:
            raise ValidationError("We're sorry, you must be 13 or older to register")


我意识到&#34; validate_age&#34;函数链接到年龄字段,但我想做这样的事情:

class SignupForm(Form):
    lowerage = IntegerField(u'LowerAge')
    upperage = IntegerField(u'UpperAge')

    def validate_ages(form, lowerage, upperage):
        if lowerage.data < 13 && upperage.data > 65:
            raise ValidationError("We're sorry, you must be aged between 13 and 65older to register")


我意识到由于WTForms的工作方式,代码完全无法工作,但我想在两个字段上执行自定义验证并返回一条错误消息。这是可能的,如果是这样,它将如何做? 感谢

1 个答案:

答案 0 :(得分:1)

可以创建这样的自定义验证器:

class MyValidator(object):
    def __init__(self, min=13, max=65, message=None):
        self.min = min
        self.max = max
        if not message:
            message = u"We're sorry, you must be aged between {min} and {max} older to register".format(min=self.min, max=self.max)
        self.message = message

    def __call__(self, form, field):
        l = field.data and len(field.data) or 0
        if l < self.min or self.max != -1 and l > self.max:
            raise ValidationError(self.message)

然后在表格上:

class SignupForm(Form):
      lowerage = IntegerField(u'LowerAge', [MyValidator(min=13)])
      upperage = IntegerField(u'UpperAge', [MyValidator(min=13, max=65)])