1

I use the "depend" in jQuery Validation plugin in order to apply some validation rules only in specific cases. This is the code I use to do it in case I want a field required only under certain circumstances.

 fieldA: {
required: {depends: function () {
        return $('#FormName select[name="fieldB"]').val() === '10';
    }}
 }

In case I want to use the valueNotEquals rule I have a syntax like this:

fieldA:
 {valueNotEquals: "0"}

If I want to use "depends", what is the right syntax? These two attempts gave error and syntax error.

Attemp 1 (error for I could not indicate WHAT value it must not equals)

fieldA:
     {valueNotEquals: {depends: function () {
         return $('#QuestionarioForm select[name="lavoroMadre"]').val() === '10';}}

Attemp 2 (syntax error)

fieldA:
     {valueNotEquals: "0" {depends: function () {
         return $('#QuestionarioForm select[name="lavoroMadre"]').val() === '10';}}
Sparky
  • 98,165
  • 25
  • 199
  • 285
Sasha Grievus
  • 2,566
  • 5
  • 31
  • 58

1 Answers1

3

Your code:

fieldA:
 {valueNotEquals: "0"}

Quote Title:

"How to add a “depends” condition on valueNotEquals rule in jQuery Validation plugin?"

Your code is not working because there is no such rule or method called valueNotEquals in the jQuery Validate plugin.

Documented rules & methods: http://jqueryvalidation.org/category/methods/


You'll have to write your own custom rule using addMethod():

jQuery.validator.addMethod("valueNotEquals", function(value, element, params) {
    return this.optional(element) || (value != params[0]);
}, "Please specify a value that is not equal to {0}");

And declare the rule:

fieldA: {
    valueNotEquals: [0]
}

DEMO of custom method: http://jsfiddle.net/cF3p5/


Now you wouldn't need to use depends. Simply edit this custom function so that it behaves as you want. Maybe something more like this...

jQuery.validator.addMethod("valueNotEquals", function(value, element, params) {
    if ($('#QuestionarioForm select[name="lavoroMadre"]').val() === params[1]) {
        return (value != params[0]);
    } else {
        return true;
    }
}, "Please specify a value that is not equal to {0}");

And declare the rule:

fieldA: {
    valueNotEquals: [0, 10]
}
Sparky
  • 98,165
  • 25
  • 199
  • 285
  • Power of copy/paste on code made a lot of time ago. I have totally forgot that self made function. Your custom method works perfectly! Thanks a lot! – Sasha Grievus Oct 01 '13 at 12:22