Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 296
Joe Avatar asked Sep 25 '13 22:09

Joe


People also ask

What is ignore in jQuery validation?

It's an array of jquery selectors. If the element matches the selector, it is ignored. By default it is [":hidden"] which is why making it [] makes it allow hidden elements.

How remove validation message after field is valid?

Adding an else statement to return the value of your error message span to a non-error state could correct this. this should display your error msg and return it to blank when a valid input is present.


1 Answers

  • 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/

like image 69
Sparky Avatar answered Sep 19 '22 16:09

Sparky