ParlseyJS - remove validation from disabled fields

2019-08-22 06:31发布

just started using ParlseyJS for some new work we are doing.

I am having an issue whereby I hide and disable a bunch of dropdown lists based on a dropdown value (in a form). When I submit this form, these fields continue to be validated. These fields are being disabled via jQuery as such:

minage.removeAttr('data-parsley-minagecheck').attr('data-parsley-excluded', '').attr('disabled', 'disabled');
maxage.removeAttr('data-parsley-maxagecheck').attr('data-parsley-excluded', '').attr('disabled', 'disabled');
xxx.removeAttr('data-parsley-xxxcheck').attr('data-parsley-excluded', '').attr('disabled', 'disabled');
yyy.removeAttr('data-parsley-yyycheck').attr('data-parsley-excluded', '').attr('disabled', 'disabled');

You will notice that I am also removing the custom validation checks and I am adding the excluded field to the attributes of the dropdown lists.

How can I stop them from being validated?

I updated my Parsley.js file to set ParsleyDefaults as such:

excluded: 'input[type=button], input[type=submit], input[type=reset], input[type=hidden], [disabled]',

1条回答
Melony?
2楼-- · 2019-08-22 07:09

After you bind Parsley to your form, it is not enough to remove the attributes. This is because Parsley will create a ParsleyForm object with the constraints for that form.

Also, the excluded option will be taken into account at the moment where Parsley is binded to the form. In your case, the fields are not yet disabled, so they will be taken into account for validation purposes.

What you need is to destroy and apply parsley after you have removed the attributes, so ParsleyForm doesn't containt those fields. If you are using Parsley v2 you should add this code after the removal or insertion of the attributes:

$("#myForm").parsley().destroy();
$("#myForm").parsley();

Also take note, as of jQuery 1.6 the .attr() states

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.

So you should use

minage.removeAttr('data-parsley-minagecheck')
    .attr('data-parsley-excluded', '').prop('disabled', true);
查看更多
登录 后发表回答