You can set the required property in the flask-form. But what if I need mandatory not two fields, but at least one of them (telephone and email, for example)?
- If it were on pure html + js, then before sending the form I checked if both fields are empty, then swear that at least one must be filled in - gil9red
- @ gil9red well, if you mean an educational project, it will come down, but it’s not safe at all - kot_mapku3
- Well, yes, the server also needs to be checked, and then a query will arrive by the browser and hello 5xx error :) - gil9red
- @ gil9red I just thought it was right to indicate in WTForms a choice of two, apparently, it is impossible ( - kot_mapku3
- oneI did not say that in WTForms it is impossible, but supported your comment about insecurity - gil9red
|
1 answer
There will have to add your own validator. Documentation on the topic: http://wtforms.simplecodes.com/docs/1.0.1/validators.html#custom-validators
For example:
from wtforms.validators import DataRequired class RequiredIf(DataRequired): """Validator which makes a field required if another field is set and has a truthy value. Sources: - http://wtforms.simplecodes.com/docs/1.0.1/validators.html - http://stackoverflow.com/questions/8463209/how-to-make-a-field-conditionally-optional-in-wtforms """ field_flags = ('requiredif',) def __init__(self, other_field_name, message=None, *args, **kwargs): self.other_field_name = other_field_name self.message = message def __call__(self, form, field): other_field = form[self.other_field_name] if other_field is None: raise Exception('no field named "%s" in form' % self.other_field_name) if bool(other_field.data): super(RequiredIf, self).__call__(form, field) |