How can I dynamically add and remove form fields to be validated by Parsley.js?

随声附和 提交于 2019-11-28 23:31:07

Once the new field has been added to Parsley, you need to add the required constraint to that field.

//add corresponding models select to parsely
$('#registrations').parsley('addItem', '#'+manufacturer+'-models');

//add required constraint 
$('#'+manufacturer+'-models').parsley('addConstraint', {
    required: true 
});

Update (April 10, 2014)

The above works for Parsley.js 1.x but not for Parsley 2.x.

Parsley 2.x doesn't use addItem, removeItem, addConstraint, or removeConstraint.

Instead, Parsley 2.x will automatically detect changes in your form based on the data attributes each input has. In the above example, if you wanted to add a new item to Parsley, you would do the following:

//destroy parsley
$('form').parsley().destroy();

//set required attribute on input to true
$('input').attr('data-parsley-required', 'true');

//reinitialize parsley
$('form').parsley();

Likewise, if you wanted to remove an item from Parsley, you would do:

//destroy parsley
$('form').parsley().destroy();

//set required attribute on input to false
$('input').attr('data-parsley-required', 'false');

//reinitialize parsley
$('form').parsley();
Constant Meiring

I had this issue while working with validates-if-empty set to true. Simply setting this to false didn't have any effect. I had to actually remove the attributes. On validation parley automatically detected the changes.

$('input').removeAttr('data-parsley-required');
$('input').removeAttr('data-parsley-validate-if-empty');

Update for 2019, parsley.js version 2.8.1:

You do not need to destroy parsley on the form and re-initialize it. Instead, you can just use refresh as follows:

$('form').parsley().refresh();

Destroying parsley isn't always desired as this will cause any currently existing validation errors and their messages to disappear.

You can use the above refresh statement after dynamically adding or removing fields on your form, and parsley will find them.

See the documentation from Parsley in the section titled "Forms" under "Methods": http://parsleyjs.org/doc/index.html#usage-form

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