Wednesday, December 7, 2011

Client-Side Model-Aware Validation in MVC3

Just a note so mostly, I remember.

I've been working with Nick Riggs' Foolproof validation in MVC3, trying to get more complex scenarios in place, and needed to write the client validation.  He has a great post for MVC2 at, but it doesn't cover MVC3.

After some research, etc., here is what I came up with for something very simplistic, where it's just making sure a value is set, etc...

$(function () {

    jQuery.validator.addMethod('listrequirediftrue', function (value, element, param) {
        if (param) {
            return $('#' + $(element).attr('id') + ' option:selected').length > 0;

        return true;
    }, '');
    jQuery.validator.unobtrusive.adapters.add('listrequirediftrue', {}, function (options) {

        if (options.message) {
            options.rules['listrequirediftrue'] = true;
            options.messages['listrequirediftrue'] = options.message;

} (jQuery));

I just need to now figure out for more complex scenarios, like when you have a RequiredIf, but dependent on when another dropdown has a certain value.  Nick has the RequiredIfAttribute, but when you're validating based on an entire model, where the property to be validated is not at the same level as the property whose value is the "RequiredIf" property, you have to use the ModelAware style of validation... will update when I have an answer.

No comments: