简体   繁体   中英

WTForms inline validation of more than 1 field

I am using WTForms validation and I want to perform an operation on two fields and then return one error message.

I know that I can do this:

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")


I realise that "validate_age" function is linked to the age field but I want to do something like this:

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")


I realise that code totally wouldn't work because of the way WTForms works but I want to perform custom validation on two fields and return one error message. Is this possible and if so how would it be done? Thanks

Can create a custom validator like this:

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)

then on the form:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM