Reputation: 1195
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
Upvotes: 0
Views: 1308
Reputation: 10397
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)])
Upvotes: 2