Is there a way to implement a validation in WTFforms that enforces the fact that at least one of the fields is required?
For example, I have two StringField
s and I want to make sure the user writes something in at least one of the fields before clicking on "submit".
field1 = StringField('Field 1', validators=[???])
field2 = StringField('Field 2', validators=[???])
What should I write in place of the ???
? InputRequired()
in this case wouldn't do the job as I need to assign it to one of the fields or to both. How can I do that?
Override your form's validate
method. For example:
class CustomForm(FlaskForm):
field1 = StringField('Field 1')
field2 = StringField('Field 2')
def validate(self, extra_validators=None):
if super().validate(extra_validators):
# your logic here e.g.
if not (self.field1.data or self.field2.data):
self.field1.errors.append('At least one field must have a value')
return False
else:
return True
return False
Note, you can still add individual validators to the fields e.g. input length.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With