Reputation: 61
I have a form with a couple of fields in it. The class that hold the form looks like
class TestForm(Form):
some_stuff_1 = IntegerField('Cool Bucket', description="Cool bucket",default=0,validators[validators.Optional(),validators.NumberRange(0, 100)])
some_stuff_2 = IntegerField('Boring Bucket', description="Boring bucket",default=0,validators[validators.Optional(),validators.NumberRange(0, 100)])
some_stuff_3 = IntegerField('Funny Bucket', description="Funny bucket",default=0,validators[validators.Optional(),validators.NumberRange(0, 100)])
some_stuff_4 = IntegerField('Amazing Bucket', description="Amazing bucket",default=0,validators[validators.Optional(),validators.NumberRange(0, 100)])
The above works fine. But now i have a extra condition where i want to validate that the user should not enter all 0
for all 4 fields. So basically i am looking for a custome validation here which should say flash me a message if the user entered 0 on all four fields. I have taken the look at flask wtforms custom validation, but it just applies to a one field at a time, here i am trying to apply the validation to a couple of fields.
Can someone guide me how to do so.
Upvotes: 1
Views: 921
Reputation: 4765
The trick is to connect into the validation hook and write your own test.
class TestForm(FlaskForm):
val1 = IntegerField('Cool Bucket', description="Cool bucket",default=0,validators[validators.Optional(),validators.NumberRange(0, 100)])
val2 = IntegerField('Cool Bucket', description="Cool bucket",default=0,validators[validators.Optional(),validators.NumberRange(0, 100)])
def validate(self):
rv = FlaskForm.validate(self)
if not rv:
return False
test = (self.val1.data == 0) and (self.val2.data == 0)
if test:
self.val1.errors.append('Val1 and 2 cannot be 0')
return False
return True
Upvotes: 2