Click here to Skip to main content
15,886,019 members
Articles / Web Development / HTML

Custom Validation Message Helper in ASP.NET MVC

Rate me:
Please Sign up or sign in to vote.
3.50/5 (3 votes)
24 Oct 2015CPOL1 min read 21K   309   5  
Writing Custom Validation Message Helper extension in ASP.NET MVC

Introduction

I wrote an earlier post about Creating Custom Html Helpers in ASP.NET MVC which emphasized how we can write custom html helper extensions in ASP.NET MVC according to the need, so that we can reuse them in the whole application, instead of writing plain html in View.

The example in that article was using ActionLink, today I am going to tell how we can implement custom Validation Message helper. I wanted to modify the validation message displaying in my application so that it displays * in front of required fields and the error message in tooltip of it like:

For that, add a class in the project and add an extension method which will render our custom html that will be displayed for error message:

C#
namespace CustomValidationMessageHelper.Helpers
{
    public static class Validator
    {
        public static MvcHtmlString MyValidationMessageFor<TModel, 
		TProperty>(this HtmlHelper<TModel> helper, 
		Expression<Func<TModel, TProperty>> expression)
        {
            TagBuilder containerDivBuilder = new TagBuilder("div");
            containerDivBuilder.AddCssClass("tip_trigger");
            containerDivBuilder.InnerHtml = "*";

            TagBuilder midDivBuilder = new TagBuilder("div");
            midDivBuilder.AddCssClass("classic");
            midDivBuilder.AddCssClass("tip");
            midDivBuilder.InnerHtml = helper.ValidationMessageFor(expression).ToString();

            containerDivBuilder.InnerHtml += midDivBuilder.ToString(TagRenderMode.Normal);

            return MvcHtmlString.Create(containerDivBuilder.ToString(TagRenderMode.Normal));
        }
    }
}

and then define the following CSS in a CSS file, in my case it is site.css or you can add it in the view:

.validated {
    border-color: #DCE4EC !important;
}

textarea, input[type="text"], input[type="password"], 
input[type="datetime"], 
	input[type="datetime-local"], input[type="date"], 
	input[type="month"], 
	input[type="time"], input[type="week"], 
	input[type="number"], input[type="email"], 
	input[type="url"], input[type="search"], 
	input[type="tel"], input[type="color"], 
	.uneditable-input {
    padding: 3px 3px;
    border: 1px solid #DCE4EC;
}
        
.tip {
    background: none repeat scroll 0 0 #FFFFFF;
    border: 1px solid #808080;
    border-radius: 10px;
    box-shadow: 0 1px 10px rgba(32, 32, 32, 0.5);
    color: red;
    display: none;
    font-size: 12px;
    font-style: normal;
    margin-left: 10px;
    margin-top: -24px;
    padding: 4px;
    position: absolute;
    z-index: 999999;
}

.tip_trigger {
    width: 10px;
    float: right;
    color: red;
    margin-left: 3px;
}

Now we have to add client side code, which I have written in jquery in a js file or directly in view, in my case, I have it in CustomValidation.js file:

$(document).ready(function () {
    //Tooltips
    var tip;
    $(".tip_trigger").hover(function () {
        console.log("hovered");
        tip = $(this).find('.tip');
        console.log($(this).find('.tip').find('span').html())
        if ($(this).find('.tip').find('span').html() != '') {
            $(this).find('.tip').show(); //Show tooltip
        }
    }, function () {
        $(this).find('.tip').hide(); //Hide tooltip 
    });

    ////Required fields
    $('input').each(function () {
        var req = $(this).attr('data-val-required');
        if (undefined != req) {
            $(this).css("border-color", "#DA9BA2")

        }
        if ($(this).val() != '') {

            $(this).addClass("validated");
        }
    });

    $('input').blur(function () {

        if ($(this).val() != '') {

            $(this).addClass("validated");
        }
        else {

            $(this).css("border-color", "#DA9BA2")
        }
    });
});

Now in the View, add the reference to the related js and css files in the head section of View:

<link href="@Url.Content("~/Content/site.css")"
    rel="stylesheet"/>
<script src="@Url.Content("~/Scripts/jquery-1.9.1.js")"></script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.js")"
    type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")"
    type="text/javascript">
</script>
<script src="@Url.Content("~/Scripts/CustomValidation.js")"
    type="text/javascript"></script>

Now in your view, add using statement of the namespace and now you can access the Helper method in the View:

C#
@model CustomValidationMessageHelper.ViewModels.SignUpViewModel
@using CustomValidationMessageHelper.Helpers
@{
    Layout = null;
}

@Html.TextBoxFor(model => model.FirstName, new { @class = "form-control input-sm" })
@Html.MyValidationMessageFor(model => model.FirstName)

The sample project can be downloaded from here.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Pakistan Pakistan
Ehsan Sajjad is a Microsoft Certified Professional, Microsoft Certified C# Specialist and he is also among the top users on StackOverflow from Pakistan with 50k+ reputation at time of writing this and counting.

He is a passionate software developer with around 5 years of professional experience in Microsoft Technologies both web and desktop applications and always open to learn new things and platforms especially in mobile application development and game development.

Some Achievements :

  • 5th Top Contributor from Pakistan on Stackoverflow.com
  • Top User in ASP.NET MVC from Pakistan on Stackoverflow.com
  • 21st June 2017 - Article of the Day - ASP.NET Community (Beginners Guide on AJAX CRUD Operations in Grid using JQuery DataTables in ASP.NET MVC 5)
  • 19th April 2017 - Article of the Day - ASP.NET Community (ASP.NET MVC Async File Uploading using JQuery)
  • March 2017 - Visual C# Technical Guru Silver Medal on Microsoft Tech Net Wiki Article Competition
  • 20 January 2017 - Article of the Day - ASP.NET Community (Async File Uploading in ASP.NET MVC)
  • 22nd September 2016 - Article of the Day - ASP.NET Community (GridView with Server Side Filtering, Sorting and Paging in ASP.NET MVC 5)
  • 22nd August 2016 - Article of the Day - ASP.NET Community (Beginners Guide for Creating GridView in ASP.NET MVC 5)
  • December 2015 - C-SharpCorner Monthly Winner

Comments and Discussions

 
-- There are no messages in this forum --