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

假装没事ソ 提交于 2019-12-19 03:34:44

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/26002630/validate-set-of-fields-only-if-radio-button-is-checked-conditional-validation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!