Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
761 views
in Technique[技术] by (71.8m points)

parsley.js - Validate set of fields only if radio button is checked (conditional validation)

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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...