Translate

Monday, March 23, 2015

Custom jQuery validation plugin client side validation rules

When using jQuery Validation plugin setting up a new validator for a Html form is easy. Adding custom rules for validation is just as easy. Creating a custom rule on the client side could be more efficient than doing server side validation after the form is submitted.
Take for instance this javascript that creates a Validation object for a Html5 input element of type number:
// your Validation object
Var myValidator;

// Place custom validation rule here
// setting up the rules and message for the input element
myValidator = $( "#form1" ).validate({
    rules: {
        input1: { // selector of your input textbox
            digits: true,
            minlength: 9,
            maxlength: 9,
            messages: {
                digits: "Value has to be a number",
                minlength: $.validator.format("Value {0} is to low"),
                maxlength: $.validator.format("Value {0} is too high")
            }
        }
    },
    showErrors: function(errorMap, errorList){
            // place you validation error summary rendering code here
        });
    }
});
Now if you had a javascript function bound to the input element's keyup, input events your call to validate the value of the input element could be similar to the following javascript:
$( "#input1" ).bind( "keyup input", function(e) {
        myValidator.element( "#input1" );
    }
});

Now the custom rule part. Take for instance you wanted to prevent a value to be submitted that was already on display in a different element on the form. Instead of performing server side validation or making a separate ajax call, add a custom validation method to the jQuery Validation plugin. (The syntax is available at http://jqueryvalidation.org/jQuery.validator.addMethod/).

// Place custom validation rule here
// addMethod ( method-name-string, function(value, element){
//  validation code
//}, validation-message-string );
// e.g.
$.validator.addMethod( "notequalto", function( value, element ) {
    var currentVal = $( "#txtBoxCurrentValue" ).text();
    if ( value === currentVal ) {
        return false;
    } else {
        return true;
    }
}, "That value is already set" );

Now update you rules section for input1 in your validator object to be:
    rules: {
        input1: { // selector of your textbox
            digits: true,
            minlength: 9,
            maxlength: 9,
            notequalto: true, // no quotes around the new method name, must validate to true
            messages: {
                digits: "Value has to be a number",
                minlength: $.validator.format("Value {0} is to low"),
                maxlength: $.validator.format("Value {0} is too high")

            }