Turn on/off Jquery Validation for one input [closed]

女生的网名这么多〃 提交于 2019-12-20 09:18:29

问题


I am using the same form to add and edit values. During addition of an item, I want it to force a name check against the server, which it does. However, during edit mode I want it to not validate, since the name may not change. I tried to set the ignore property in the validator to the "ignore" class, based on the documentation, link below. I use that same class name in the name input, but that does not work. It kept validating against the server. Any thoughts?

URL to the code I am using, primarily the validate function. http://jqueryvalidation.org/validate/

Based on the the documentation for the ignore property, it states:

Elements to ignore when validating, simply filtering them out. jQuery’s not-method is used, therefore everything that is accepted by not() can be passed as this option. Inputs of type submit and reset are always ignored, so are disabled elements.

I looked in the code and could only see it impacting clean up of errors during the call to validator.resetForm(). This part of the code works correctly.


回答1:


  • You cannot toggle the jQuery Validate plugin on/off for the form or for individual field elements. There is no method or workaround for this.

  • The ignore option is set within the .validate() call, which is a "one-time" initialization of the plugin, so you cannot change or toggle options dynamically. Any subsequent calls to .validate() are always ignored.

After initializing the plugin with .validate(), your only solution would be to use the .rules() method to dynamically 'add' and 'remove' rules for individual field elements. Don't be fooled by the 'add' terminology... this method also allows you to overwrite existing rules, so you don't necessarily have to 'remove' them first.

To dynamically set the field as required:

$('#myfield').rules('add', {
    required: true   // set a new rule
});

To dynamically set the field as not required:

$('#myfield').rules('add', {
    required: false   // overwrite an existing rule
});

OR

$('#myfield').rules('remove', 'required');  // removes only specified rule(s)

OR

$('#myfield').rules('remove');  // removes all rules for this field

Documentation: http://jqueryvalidation.org/rules/



来源:https://stackoverflow.com/questions/19016053/turn-on-off-jquery-validation-for-one-input

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