Ray
Ray

Reputation: 3060

jquery validate field equalTo element only if another field a certain value

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

Upvotes: 2

Views: 5908

Answers (1)

nirazul
nirazul

Reputation: 3955

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'."
        }
    }

});

Upvotes: 4

Related Questions