client-side validation in custom validation attribute – asp.net mvc 4

Take a look at this: http://thewayofcode.wordpress.com/tag/custom-unobtrusive-validation/

Using this tutorial I got my custom validation code running with no problem. The only difference I can spot in your code is the way you created the $.validator.unobtrusive.adapters.add function. The parameters are a little bit different but, maybe, the problem is just that you have not defined the rule part of your adapter.

Try using something like this:

$.validator.unobtrusive.adapters.add("requiredif", ["requiredif"], function (options) {
    options.rules["requiredif"] = "#" + options.params.requiredif;
    options.messages["requiredif"] = options.message;
});

or this

$.validator.unobtrusive.adapters.add("requiredif", function (options) {
    options.rules["requiredif"] = "#" + options.element.name.replace('.', '_'); // mvc html helpers
    options.messages["requiredif"] = options.message;
});

About the rule (taken from the link):

The jQuery rules array for this HTML element. The adapter is expected
to add item(s) to this rules array for the specific jQuery Validate
validators that it wants to attach. The name is the name of the jQuery
Validate rule, and the value is the parameter values for the jQuery
Validate rule.

Leave a Comment