Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate set of fields only if radio button is checked (conditional validation)

Tags:

parsley.js

I have a form with two sets of fields:

  • "Contact information" (17 fields)
  • "Company information" (5 fields)

There is a radio with the question "Do you have a company?" that is related to the company information. If the radio is "Yes", the company fields must be filled and validated. If the radio is "No", the company fields should be ignored.

I'm not sure about the best way to manage this problem.

  1. By switching the attribute disabled of the company fields according to the state of the radio button and excluding all the disabled fields in the parsley option

    $('#adminForm').parsley({excluded: '[disabled]'});
    
  2. With two data-parsley-group and a validation of one or two blocks according to the state of the radio button

I'm trying to do it with an example on jsfiddle (but without success).

like image 453
Lauradev Avatar asked Sep 23 '14 18:09

Lauradev


1 Answers

Parsley documentation states the following about data-parsley-group

Assign a group to a field for specific group validation. eg: data-parsley-group="signup". This way, you could only validate a portion of a form and not all the fields. Can be multiple. eg: data-parsley-group='["foo", "bar"]'

One could think that you could use data-parsley-group to validate only a portion of the form and, after validation, the form would submit. This is not correct.

data-parsley-group is intended to be used in multi-step forms, where the entire form must be validated, and validation is applied to one or few groups at a time. The form is submitted once all groups are validated.

What you need is:

  1. If company is not checked: Validate only the first fields and ignore company fields.
  2. If company is checked: Validate all form fields.

So, the form is the same but sometimes the form has more fields. I suggest you would use disabled to address the issue. When company is checked, show the fields, otherwise hide the fields and make them disabled.

When binding parsley to the form, add the :disabled to the excluded option so Parsley can ignore this fields.

I have updated the JSFiddle to meet your needs.

like image 106
Luís Cruz Avatar answered Sep 20 '22 12:09

Luís Cruz