ASP.NET MVC: Displaying Client and Server Side Validation Using Error Icons


In a previous post I showed how you could display both client and server side validation using qTip tooltips. In this post I will show how you can display an error icon next to the field that is invalid and then when the user hovers over the icon, display the error message (demonstrated below).

As done previously I will be using the same example project from this post where we created a dialog form which was submitted via Ajax.

You can download the complete solution for this example here.

First, the error icon. I utilized the ui-icon-alert class that comes with jQuery UI to display the error icon. But, to get the icon to display correctly without having to create a containing div element around the icon, we need to add a new class to the jquery.ui.theme.css file. Open up the default jquery.ui.theme.css file or if you have added a custom theme, the jquery-ui-[version number].custom.css file and find the states and images sub section under the Icons section. Add the following css class to the list of classes there.

.ui-state-error-icon { display:inline-block;  width: 16px; height: 16px; background-image: url(images/ui-icons_cd0a0a_256x240.png);  }

This class will allow a 16 x 16px icon from the error images png to be displayed in an empty element.

Next we need to change the onError function in the jquery.validate.unobtrusive.js javascript file. Open that file and replace the onError function with that shown below.

function onError(error, inputElement) {  // 'this' is the form element        
    var container = $(this).find("[data-valmsg-for='" + inputElement[0].name + "']"),
    replace = $.parseJSON(container.attr("data-valmsg-replace")) !== false;

    container.removeClass("field-validation-valid").addClass("field-validation-error");
    error.data("unobtrusiveContainer", container);

    if (replace) {
            
        // Do not display the error message
        //container.empty();
        //error.removeClass("input-validation-error").appendTo(container);

        // If the error message is an empty string, remove the classes
        // from the container that displays the error icon.  Otherwise
        // Add the classes necessary to display the error icon and
        // wire up the qTip tooltip for the container
        if ($(error).text() == "") {
            container.removeClass("ui-state-error-icon").removeClass("ui-icon-alert");
        }
        else {
            container.addClass("ui-state-error-icon").addClass("ui-icon-alert");

            $(container).qtip({
                overwrite: true,
                content: $(error).text(),
                style: {
                    classes: 'ui-tooltip-red'
                }
            });
        }
    }
    else {
        error.hide();
    }
}

Here instead of displaying the error message in associated container, we are displaying the alert icon and wiring up a qTip tooltip to display the error text. (Make sure in your Layout or MasterPage that you reference the jquery.validate.unobtrusive.js javascript file not the jquery.validate.unobtrusive.min.js file.)

If you run the application now all client side errors will be displayed using little error icons as pictured above and if the user hovers over the icon, the error message will be displayed in the tooltip.

To make server side validation messages appear in the same way we need to add another javascript function to each page. Create a new javascript file named jquer.qtip.validation.js and paste the following code into it.

$(function () {
    // Run this function for all validation error messages
    $('.field-validation-error').each(function () {

        // Get the error text to be displayed
        var errorText = $(this).text();

        // Remove the text from the error message span
        // element and add the classes to display the icon
        $(this).empty();
        $(this).addClass("ui-state-error-icon").addClass("ui-icon-alert");

        // Wire up the tooltip to display the error message
        $(this).qtip({
            overwrite: true,
            content: errorText,
            style: {
                classes: 'ui-tooltip-red'
            }
        });     
    });
});    

Here we are doing the same thing we did for client side validation except we are iterating over all elements with the field-validation-error class and removing its text, displaying the icon, and placing the error message in the tooltip. Make sure that on every form where you have server side validation displayed that you reference the jquery.qtip.validation.js javascript file.

There you have it. Client and server side validation displayed using error icons and tooltips.

About these ads

12 Responses to “ASP.NET MVC: Displaying Client and Server Side Validation Using Error Icons”

  1. Eranga Says:

    Thanks a lot.

  2. Mark Says:

    The server side does not work. I’m sure I’m doing something wrong. A view source verified that this file jquery.qtip.validation.js is on the page. Does it run automatically or so I have to “hook” it up somehow. Placing a breakpoint on it in firebug and the breakpoint doesn’t hit.

    Thanks

  3. Mark Says:

    I should add that I’m making the post vis Ajax.BeginForm. Does your solution work server side for an ajax post? I do get the validation, it’s just the plain old vanilla mvc ugly messages rather than the qtips as I get on the client.

    Thank you

    • Nick Olsen Says:

      If you are using the Ajax.BeginForm helper then the page is not reloaded and the jquery.qtip.validation script will not be run again. All you need to do is put the code in the jquery.qtip.validation in its own function so you can call it and then in the success function of the Ajax.BeginForm helper, call that function. Do something like this:

      jquery.qtip.validation.js
      function qtipifyValidation() {
      // Code here from jquery.qtip.validation.js
      }

      Html
      @using(Ajax.BeginForm(new AjaxOptions() { OnSuccess = “qtipifyValidation” })) {

      }

  4. Nigussie Abate Says:

    Hello Mr.Nick Olsen!
    It is very nice application and i like to work with asp.net but
    I am beginner to ASP.net and i do not know much about it.
    so,can I have some introductions and Tutorials?

  5. Bruno Says:

    Great Posts!

    • Nick Olsen Says:

      Thank you. Glad you enjoyed them!

  6. Ufi Says:

    Hi Nick. I found a bug in your DialolForm.js. On line 3:
    $.ajaxSetup({ cache: false; });
    should remove the semicolon:

    $.ajaxSetup({ cache: false });

    otherwise great article :)

    cheers

    marko

    • Nick Olsen Says:

      Good catch. Sorry about that. I will fix the project

  7. DK Says:

    Hi there !
    Have you tried to do it on VS2012 ? I don’t get to make it works there…
    I’m using Jquery 1.9 and Jquery UI1.10.

    Thanks

    • DK Says:

      It works greatly with Jquery 1.8.3 and Jquery UI 1.9.2 but not with Jquery 1.9 and Jquery UI1.10.

  8. Greg Says:

    How to get a handle on server side validation message before rendering in span ? The field-validation-error is visible prior to the qtip popping (age field).

    Thanks


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.

Join 67 other followers

%d bloggers like this: