Monday, July 8, 2013

Show error message as tooltip in ASP.NET MVC

There are many ways form validation messages can be shown in web application. One of the typical error message is to show star(*) character beside the input box and show the actual message as a tooltip. I have been developing a web application using asp.net mvc where my clients wants to display error message as a tooltip.

In my asp.net mvc application, I am using data annotation with JQuery validation for validating my model. I will not go into the details of data annotation and JQuery validation since it is not scope of this post.

JQuery validation shows the full error message beside the input box like the following screenshot:


I didn't find any straight forward way to show error message as star(*) character. In order to achieve this, we need to write following javascript code:

$(document).ready(function () {
        var settngs = $.data($('form'), 'validator').settings;
        var oldErrorPlacement = settngs.errorPlacement;
        settngs.errorPlacement = function (error, inputElement) {
            var message = error.html();
            error.html("*");
            error.attr("title", message);
            oldErrorPlacement(error, inputElement);
        };
    });

The above code snippet overrides the errorPlacement event of JQuery validator. Inside the event, the code is self explanatory.

Now, the error message will look like following screenshot:


Hope this helps!


No comments: