How to change the way jQuery.validate handles error messages

I use the jQuery.validate plugin to handle most of my html form validation. This is by far the most widely used jQuery plugin for form validation. To reinforce the importance and quality of this plugin a bit more, Microsoft recently announced that they were dropping their own validation implementation in favor of jQuery.Validate for ASP.NET MVC 3. This plug-in is really outstanding, but best of all it is incredibly simple to customize.

Right, so the the topic of this post. Whenever an element being validated by jQuery.Validate in your page is found to be invalid, jQuery.validate  – referred to as “VAL” from now on – adds a label element next to it showing the error message for the particular validation being performed. This is fine for most situations, however sometimes you need to handle scenarios where the default placement of the error message is not quite right. The creators of VAL anticipated this and provided several built-in ways to customize this behavior with just a little bit of effort. These are the three scenarios I find myself using most often:

Scenario 1: I want to show all my error messages inside a single error container as a UL element

                   $("#addEventForm").validate({
                            errorContainer: "#errorContainer",
                            errorLabelContainer: "#errorContainer",
                            errorElement: "li”

                     })

errorContainer : is a space separated list of element ids that will be shown when the form is invalid and hidden when the form is valid.

errorLabelContainer : this is the id (or any jquery selector string) of the element that will contain the error labels generated for each invalid field

errorElement : by default the error element generated by VAL is a label control. If your container is a UL then you can set this variable to “li” in order to generate LI elements instead of label elements.

 

Scenario 2: I want to show the error control before the field it is validating rather than after it (which is the default location)

 

                    $("#addEventForm").validate({
                            errorPlacement: function (error, element) {
                                error.insertBefore(element);   
                             }          
                        })

errorPlacement: is the function that is called by VAL to inject the error element into the DOM. By overriding this function we are able to place it anywhere we want. Both the error and element parameters passed into the function are jQuery objects. Sky is the limit as to what you can do here.

 

Scenario 3: I have a form with two input fields, first name and last name. They are located next to each other, and they are both required. When either one of these fields is empty I want to show the error label generated by VAL inside a div element named “nameError” which is placed bellow the two input controls.

To do this we are going to use the same trick as in scenario 2 except that we are going to inspect the name of the invalid element being passed into the errorPlacement function and do a custom injection of the error message for just the first and last name. For all other errors we do the default, which is append the error label next to the invalid input control.

                    ("#addEventForm").validate({
                            errorPlacement: function (error, element) {
                                     if (element.attr(“name”) == “fname” || element.attr(“name”) == “lname”)
                                            $(“#nameError”).append(error);
                                     else
                                             error.insertAfter(element);
                             }          
                        })

 

That’s it!

Enjoy!

About these ads

32 responses to this post.

  1. Posted by Marcin Wasik on April 12, 2011 at 1:12 pm

    Hello,
    What’s the “addEventForm” ? I copied the first example, changed only the “errorContainer” to my container but it didn’t work.
    Marcin

    Reply

  2. Posted by Marcin Wasik on April 12, 2011 at 1:46 pm

    I changed also “addEventForm” to the name of my form and still nothing. Does anyone know what could be the problem ?
    Marcin

    Reply

  3. Posted by Jon on June 29, 2011 at 3:44 am

    Hey,

    Thank you bunches for your explanation. I have a quick question though.

    Is the code you wrote above purely for explanation? I was trying out your 3rd scenario code and it’s breaking all other code on the page as well throwing my syntax coloring off.

    $(document).ready(function(){
    $(“#regform”).validate({
    errorPlacement: function (error, element) {
    if ((element.attr(“name”) == “firstname” || element.attr(“name”) == “lastname”)) {
    $(“.error-wrapper”).append(error);
    } else {
    error.insertBefore(element);
    }
    }
    });
    });

    Reply

  4. Posted by Jon on June 29, 2011 at 5:50 am

    So I had some of my brackets off I think.

    However in the process of trying to solve that I think I found a better (well at least easier) solution for your third scenario.

    The second answer by Stefan Morrow here mentions that you can specify a fake label and the validate plugin will fill it with the error message. This doesn’t seem to be in the documentation but it works for me. http://stackoverflow.com/questions/2969381/jquery-validation-plug-in-custom-error-placement

    Using that workaround you can then specify the two input in a group which is in the documentation here: http://docs.jquery.com/Plugins/Validation/validate (sorry they don’t seem to support deep linking)

    It looks like this:
    $(“#regform”).validate({
    groups: {
    username: “firstname lastname”
    }
    })

    That and the dummy label in the markup for=”username” is all you need.

    Reply

  5. So I have a really dumb question I think. First of all, I am very new to JQuery (though am familiar with JS and DOM, etc. I am using (attempting to use) this pluging because it seems fantastic. The validation, of course, is no problem. However, the placement of the error messages are. While I will need a few more options than listed above, this is a great start to learning what needs and can be done. So thanks for that.

    So, the dumb question – where in the world do I add this? And how does it interact with the rest of the jquery.validate.js?

    Thanks!

    Mike

    Reply

  6. Okay, nevermind. Research will do a body good I suppose :). I finally used the proper search terms and found what I was looking for. However, one other question – is it possible to use multiple validate() to handle different needs, or will I have to incorporate it into one function?

    Thanks!

    Mike

    Reply

    • Hi Mike.

      At the bottom of your page, when you are setting your form up for validation, you do so by calling

      $(“#formid”).validate({ … });

      The options I mention above are passed as an object to the validate method to configure the validation for the selected form (“#formid”).

      Hope this helps.

      Regards,
      Mitch

  7. Posted by Mike on November 21, 2011 at 7:32 pm

    Hi,
    I have a long form with many questions. I would like to display errors for the first 5 questions above question #1. I would like to display errors for the remaining questions above question #6. As it is now, all errors are displayed above question #1, but this requires too much scrolling up and down.

    Is it possible to have two error containers, both displaying errors for two different groups of questions?

    Thanks,
    Mike

    Reply

    • Sure, you can do a custom error validation that will inspect the name of the field that is being reported as having an error and appending the error to a div in one of the two locations you specified. If the field is 1-5 then add the error to the first div, otherwise add them to the last div.

      So you can just follow scenario two and just check for the name attribute of the element to determine if it should be placed in error container one or two.

      Hope this helps.

      Regards, Mitch

  8. I am using jquery validate for my form validations. I have displayed all the errors at the top of the form by using the below code.

    errorPlacement: function(error, element) {
    error.insertAfter($(“span#errorContainer”));
    }

    Everything is okay and working as expected but having design problem with IE7. If errors get validated success the errors message goes away but the label stays on the pages and the blank labels keep space in IE7 as i have given display:block in the css to line all of them vertically. Any help would be appreciated.

    Reply

  9. this can help you its new type of form validation plugin http://workwithphp.info/?p=16

    Reply

  10. [...] plugin method Customizing jQuery Validation: replace the default “required” validation How to change the way jQuery.validate handles error messages: override “errorPlacement”, relocate error message Share this:TwitterFacebookLike [...]

    Reply

  11. Thanks so much!

    This is exactly what I was looking for! Cheers! )

    Reply

  12. Posted by Santiago on May 20, 2012 at 3:09 pm

    Hello, this is a very Intersting tutorial certainly Helped me a lot, However, i have a question about different scenarios… I am very new to Jquery and will like to do first of all, the Error message to go Inside the input value. and also, when clicking submit, i want the ‘successs’ text to show in a lightbox if thats possible with jquery and css.. if you can please explain me that , it will be great THanks
    Santiagoo

    Reply

  13. Posted by Gyro on June 25, 2012 at 2:33 pm

    Hi Mitch, great tutorial!

    I would like to do something similar to option 2 and show the error message before the element but also to display an image of a cross next to the element.

    Currently I can display the cross image by changing the message: block to have the tag in it. But this, of course, means I dont have a text error message now. Is there a way I can have both?

    (PS My code also displays a ‘Tick’ for validated elements using the success: block)

    Reply

  14. Posted by simon on June 27, 2012 at 8:27 am

    Thanks for the help…

    Reply

  15. Posted by Teddy on August 22, 2012 at 8:47 am

    Hello, i use your first scenario, and i want to know if it is possible to personalise each error message for identificate the field with the good error message (i use a huge form).

    Reply

  16. Posted by Edu on August 30, 2012 at 12:16 am

    Its possible to show two different errors of just one invalid input ?
    Example: I got a input called “Full Name”. If the user left this field blank, i need that one message appear on a div called #error-div, AND, i need that one exclamation signal appears beside the input, in a div “called” #error-signal.
    It’s possible?
    Well, sorry for my bad english, i hope you understand it heheh
    Thanks for your help from now :)

    Reply

    • Absolutely, you can program any rules you want when you handle the error in a custom way. Just put in your logic and then show the right error message wherever you would like.

      Regards, Mitch

  17. Posted by Angeleah on September 20, 2012 at 11:55 am

    This really helped me out. Thanks!

    Reply

  18. Posted by ferry on November 7, 2012 at 5:35 am

    hi……….

    Reply

  19. Posted by ferry on November 7, 2012 at 5:36 am

    please can you give me an example..
    thnx in advance..!!!!!

    Reply

  20. Hi,

    I want to use Scenario 1: I want to show all my error messages inside a single error container as a UL element for my registration form.
    But this didn’t work.
    See this is my code:
    jQuery(document).ready(function(){

    var validator = jQuery(“#registerform”).validate({
    rules: {
    user_login: {
    required: true,
    htmltags: true,
    },
    user_email: {
    required: true,
    verifyemail: true,
    checkemail:true,

    }
    },
    messages: {
    user_login: {
    required: “”,
    htmltags: “”,
    },
    user_email: {
    required: “”,
    verifyemail: “”,
    checkemail: “”
    }

    }, // the errorPlacement has to take the table layout into account
    errorContainer: ‘#errorContainer’,
    errorLabelContainer: ‘#errorContainer’,
    errorElement: ‘li’,
    // specifying a submitHandler prevents the default submit, good for the demo
    submitHandler: function() {
    document.registerform.submit();
    },
    // set this class to error-labels to indicate valid fields
    success: function(label) {
    // set as text for IE
    label.html();
    }
    });
    jQuery.validator.addMethod(“htmltags”, checkHTMLTags);
    jQuery.validator.addMethod(“checkemail”, CheckEmail);
    jQuery.validator.addMethod(“verifyemail”, verifyEmail);
    jQuery.validator.addMethod(“checkusername”, CheckUsername);

    });

    errorContainer is my div ID where i want to display all errors. but it’s not working.

    Regards
    Seema

    Reply

  21. Acquiring certain actions omissions despite. Likewise, it’s undergone one interferance lcd from where the pulp too fruit juice are perhaps connectors. One could merely see these vitamins and nutrients via the only thirstier . of the profits whilst think about.

    Reply

  22. Just wanted to say thanks for this post. It really helped solve an issue I was having.

    Reply

  23. Posted by chester on March 11, 2014 at 11:00 pm

    what if i want to show the error message at the bottom of textbox.. what should i do??? pls help me…

    Reply

  24. Posted by Jackson on April 30, 2014 at 10:00 am

    I have questions, i noticed that when i use the same id=”” tag the error messages shows up in random places. for example.

    Now the names are different but the id’s are the same, if input test3 is wrong the error will show up in test1, is there a way to have jquery.validation.js to use the name as the identifier for the error display location as opposed to id ?

    Reply

  25. It’s hard to find your articles in google. I found it on 22 spot,
    you should build quality backlinks , it will help
    you to get more visitors. I know how to help you, just search in google – k2 seo tricks

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: