Skip to content

Customizing jQuery Validation

While doing some bug fixing and cleanup in a web application, I had the chance to go a little deeper into the jQuery user input validation framework. There are many tutorials available about implementing custom validations. But what I wanted to do was to extend the default validations with my own code, while preserving the existing functionality, and to do it site-wide.

So let’s pretend that I’d like to extend the default "required" validation in such a way that you are not allowed to enter "foo" in any form field with the "required" class. First, I need to write a function to test this:

function notFoo(value) {
    return value !== "foo";
}

Putting the custom code in a separate function makes it very easy to unit test.

Now, I’d like to replace the default "required" validation with one which first calls my custom method, and then does the regular, default validation, if it passes the custom validation. I can call jQuery.validator.addMethod, and pass "required" as the name argument. Even though this is a standard validator, supplied by the jQuery validation framework, I’m allowed to replace it with my own custom method:

jQuery.validator.addMethod("required", function(value, element, param) {
        return notFoo(value);
        },
    jQuery.validator.messages.required // use default message
    );

So far, I’ve only replaced the standard "required" validator. This is useful by itself; there may be times when you want to write code to completely replace the standard validator. If you put this code in your site master template, you will have accomplished that goal.

But my goal was to extend the default validation, not replace it. So I need to store a reference to the default "required" validator, and then call it, after calling my custom code:

jQuery.validator.methods.oldRequired = jQuery.validator.methods.required;

jQuery.validator.addMethod("required", function(value, element, param) {
        if (!notFoo(value)) {
            return false;
        }
        return jQuery.validator.methods.oldRequired.call(this, value, element, param);
    },
    jQuery.validator.messages.required // use default message
    );

I can’t call the oldRequired method directly, because it uses "this", which will point at the wrong thing if I just invoke it without call.

Before I wrap up this post, I would like to extend thanks to the folks at Stack Overflow who helped me fix a some issues in my first attempt at doing this.

{ 6 } Comments

  1. Teguh Eko Budiarto | January 27, 2010 at 5:56 am | Permalink

    I was trying to create multi step form using tab approach, and need to validate each step without actually submitting the form.
    This is exactly the remedy of my problem. Extending the required method to work only for the page that the user is in. THANK YOU!!!

  2. Garfield Lindo | March 22, 2010 at 8:16 am | Permalink

    Hi Craig,
    I’m hoping you might have some insight into an issue I’m facing with the validator.addMethod. I’ll describe below:

    Specifically my question deals with the message part of the addMethod function. I have the following code in my document.ready function.

    $(document).ready(function() {
    var message = "";
    jQuery.validator.addMethod("IsSelectionValid", function(value, element, param) {
    var result = true;

    if ($(’#auditTypeDropDownList option:selected’).val() == ‘1′ && element.id == ‘opinionDropDownList’) {
    if (value == ‘7′ || value == ‘8′) {//7 = other 8 = N/A
    result = false;
    message = "* Can use all choices except Other and N/A";
    }
    else {
    result = true;
    }
    }
    else if ($(’#auditTypeDropDownList option:selected’).val() == ‘2′ && element.id == ‘opinionDropDownList’ ||
    $(’#auditTypeDropDownList option:selected’).val() == ‘3′ && element.id == ‘opinionDropDownList’) {
    if (value == ‘8′) {
    result = true;
    }
    else {
    result = false;
    message = "* N/A is the only available option for audit opinion with this audit type";
    }
    }
    return result;
    },message);
    });

    The problem is I’m unable to get the message to be displayed. When I put the message variable in an alert I can see the text just fine. However when I put the variable in its expected place I get nothing. However if I put a string like "* Can use all choices except Other and N/A" it displays. I just don’t seem to be able to use a variable. Any thoughts?

    Response: Well, you just added a validator with an empty message. Your validation function does not run until well after the validator has already been added, so the message variable will be unassigned when you add the validator. It seems to me like you are attempting to roll two different validation rules into a single validation. Why not just make them two separate rules?

  3. Manoj | November 3, 2010 at 2:33 pm | Permalink

    Just what I was looking for.

    I wanted an optional date validation and was using the dateITA from the additionalmethods.js. However, I had a watermark in the text box due to which the date validation would always trigger.

    Extended the dateITA to my own custom function which checked if it there was a watermark or not and then if necessary called the original dateITA method. Worked like charm!

  4. jsherk | January 10, 2011 at 11:11 pm | Permalink

    Thanks for this… I was struggling with trying to figure out how to create dynamic custom messages with the addmethod and the key line was:
    jQuery.validator.messages.required // use default message

    So I used:
    $.validator.messages.nameOfMethod = ‘custom message here’;
    and it worked!

    Thanks again

  5. CB | December 23, 2011 at 12:16 am | Permalink

    Not sure if jsherk meant to replace one line with the other, but for anyone looking to do custom inline errors messages, I believe the link jsherk is talking about is supposed to go in the extra conditional code that is in the article example. Here’s my new "required":

    $.validator.addMethod("required", function(value, element, param) {
    // reg-first-name custom errors
    if (element.id==’reg-first-name’ ) {
    if( value == ” ){
    $.validator.messages.required = "Please enter your first name.";
    return false;
    } else if( !value.match(/^[A-Za-z]+$/) ){
    $.validator.messages.required = "Please enter only alpha characters ( Aa-Zz )";
    return false;
    }
    return true;
    }
    return $.validator.methods.oldRequired.call(this, value, element, param);
    },
    $.validator.messages.required // use default message
    );

  6. Peter Drinnan | July 12, 2013 at 11:41 am | Permalink

    You can also use the data-msg-required attribute and change the value dynamically when needed.

    Example:

    [input type="text" name="maxValue" data-msg-required="a custom message" id="maxValue" required]

{ 1 } Trackback

  1. [...] This post at stack overflow gave me the initial starting point, Custom date format with jQuery validation plugin and this post on jQuery forums helped with the custom error messages, Validation Plugin, changing message with addMethod and Craig Stuntz’s Customizing jQuery Validation [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

Bad Behavior has blocked 713 access attempts in the last 7 days.

Close