Flask_wtf custom validator RequiredIf not working with fieldlist / formfields
I'm trying to write a custom validator for flask\_wtf that makes a field required if another field is set to a certain value.
*Example:*
If field A == 'yes' then field B should be required. For all other values of field A no validation should run on field B.
So far i've been able to come up with the following code based on several example's i've found online:
~~~
class RequiredIf(object):
#validator which makes a field required depending on another field
#source: [https://stackoverflow.com/questions/8463209/how-to-make-a-field-conditionally-optional-in-wtforms](https://stackoverflow.com/questions/8463209/how-to-make-a-field-conditionally-optional-in-wtforms)
def __init__(self, other_field_name, trigger, message=None):
self.other_field_name = other_field_name
self.trigger = trigger
if not message:
message = 'Based on your previous input, this field is required.'
self.message = message
def __call__(self, form, field):
other_field = form._fields.get(self.other_field_name)
trigger = self.trigger
if other_field is None:
/r/flask
https://redd.it/nc4ow3
I'm trying to write a custom validator for flask\_wtf that makes a field required if another field is set to a certain value.
*Example:*
If field A == 'yes' then field B should be required. For all other values of field A no validation should run on field B.
So far i've been able to come up with the following code based on several example's i've found online:
~~~
class RequiredIf(object):
#validator which makes a field required depending on another field
#source: [https://stackoverflow.com/questions/8463209/how-to-make-a-field-conditionally-optional-in-wtforms](https://stackoverflow.com/questions/8463209/how-to-make-a-field-conditionally-optional-in-wtforms)
def __init__(self, other_field_name, trigger, message=None):
self.other_field_name = other_field_name
self.trigger = trigger
if not message:
message = 'Based on your previous input, this field is required.'
self.message = message
def __call__(self, form, field):
other_field = form._fields.get(self.other_field_name)
trigger = self.trigger
if other_field is None:
/r/flask
https://redd.it/nc4ow3
Stack Overflow
How to make a field conditionally optional in WTForms?
My form validation is working nearly complete, I just have 2 cases I don't know exactly how to solve: 1) The password field should be required of course but I also provide the possibility to log in...