Search code examples
asp.netjqueryasp.net-mvc-2client-side-validation

asp.net mvc2 microsoftMvcJqueryValidation - Include my custom client-side function


I'm using microsoftMvcJqueryValidation and I want to call my own client-side validation function for a particular field with the system so that it fires with the other auto generated client-side validation.

Is there a certain place I can call my function?

Thanks~!


Solution

  • It's not exactly what you described, but below I create a new javascript function, attach it to jQuery validator, and tell it to run on inputs with the class "monthDay":

    // add a validation method for isMonthDay...
    $.validator.addMethod("isMonthDay", function (value, element) {
        return this.optional(element) || !/Invalid|NaN/.test(new Date(value + "/2000"));
    }, "Date must be in the form Month/Day");
    // ...and associate it with the "monthDay" css class
    $.validator.addClassRules({
        monthDay: {
            isMonthDay: true
        }
    });
    

    You could do the same thing where you create a validation function and register it with $.validator. Then it's just a matter of associating the validation function with whatever input types/classes you want. $.validator's API offers various ways of doing this.

    Additionally, this does work with the auto-wiring of validation using MicrosoftMvcJqueryValidation. In fact, it doesn't make a difference if it is or not as you're simply augmenting jQuery's validator plugin, independent of how it's invoked.