Using the jQuery validation plugin I have figured out how to make a field required based on the input of another field and also how to make a field not equal to a default value – however I’m struggling to combine the two e.g. only require a field not to equal a default value when it is re quired. Here’s my code:
$(document).ready(function () {
$.validator.addMethod("notEqual", function(value, element, param) {
return this.optional(element) || value !== param;
}, "Please specify a non-default value");
$("#request").validate({
rules: {
format: {
required : true,
},
citySuburb : {
required : function(element) {
return $("#format").val()=="print"
},
notEqual : "Please enter your city."
},
}
});
});
As you can see in the example above the citySuburb field always checks to see whether it’s equal to the default value regardless of whether the field itself is required. I would really like this to make this work so that citySuburb only checks to see if it is a default value when the field is required (i.e. when ‘print’ is selected in the format field).
Any help would be greatly appreciated.
Change your notEqual method so that it accepts named parameters, e.g.
notEqual: { default: "Please enter your city.",
otherField: "#format",
otherFieldValue: "print"
}
then have the notEqual method check $(param.otherField).val() == param.otherFieldValue
.