2

Using jquery validate plugin I'm using the rule equalTo to validate a field as follows:

$('#booking').validate({

ignoreTitle: true, 
rules: {
    payments: {
        equalTo: {
            param: "#sales",
            depends: function(element) { return $("#status").val() == 'invoiced'; }
        }
    },

}
});

I can get this to work but now I'd only like this rule to apply only if a select option is a particular value. I'm lost on this and not sure how to make the equalTo rule optional dependant on another field value

I saw depends rule but cant find any documentation on this

Can anyone give me some pointers please?

I;ve created a jsfiddle to help:

http://jsfiddle.net/longestdrive/SneAF/2/

Thanks

Updated: I've tried the depends but not working as expected:

Also found some similar/duplicate questions: jQuery Validation - require field only if another field is filled and jQuery validation depends

Community
  • 1
  • 1
Ray
  • 3,018
  • 8
  • 50
  • 91
  • Since part of the issue was a misspelling, please include the HTML markup so that this question remains useful long after the links go dead. Thanks. – Sparky Aug 20 '13 at 01:36

1 Answers1

4

There were some errors in your depends-rule:

  1. You need to use another selector to get the currently selected option:
    $("#status option:selected")
  2. The value of your dependent option was Invoiced, not invoiced

This is the final result (As RobM mentioned, you could even specify more exact error messages:

Fiddle

$('#booking').validate({
    ignoreTitle: true, 
    rules: {
        payments: {
            equalTo: {
                param: '#sales',
                depends: function(element) { 
                    return $("#status option:selected").val() == 'invoiced'; 
                }
            }
        }
    },
    messages: {
        payments: {
            equalTo: "Payments must equal Sales when Status is 'Invoiced'."
        }
    }

});
nirazul
  • 3,928
  • 4
  • 26
  • 46
  • Great - thank you. Got it working in fiddle but not in form so i'll work on that or another question :) Thanks – Ray Aug 17 '13 at 22:55
  • I was about to answer this, but Nirazul beat me to it. :) You can also customize the message to be more informative, as you can see in this Fiddle: http://jsfiddle.net/SneAF/14/ – RobM Aug 17 '13 at 23:50