Udemy

Custom Validation Message Helper in asp.net mvc

Friday, October 23, 2015 0 Comments A+ a-

As i wrote earlier a post about Creating Custom Html Helpers in asp.net mvc which emphasized on 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 plan 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:

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 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:

@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