Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask WTForms: validation InputRequired for at least one field

Tags:

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 StringFields 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?

like image 882
Robb1 Avatar asked Oct 06 '20 09:10

Robb1


1 Answers

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.

like image 176
pjcunningham Avatar answered Sep 30 '22 14:09

pjcunningham