Mvc-show error message along with image

Mvc-show error message along with image, someone asked me to explain?

In this article, I will show you how to display images along with Validation message using dataannotations in mvc c#.

Here, I want to check the string length for the CategoryName using the ErrorMessage property of StringLength attribute along with HTML markup tag.

Category class: custom validation in mvc for CategoryName property.

public partial class Category

      public int CategoryID { get; set; }

        [StringLength(15, ErrorMessage = "<imgsrc='/Images/error.png' /> category name should not exceed the max lengththan 15!")]
        public string CategoryName { get; set; }
        public string Description { get; set; }


Create view: mvc form validation

        <div class="editor-label">
            @Html.LabelFor(model => model.CategoryName)
        <div class="editor-field">
            @Html.EditorFor(model => model.CategoryName)
            @Html.ValidationMessageFor(model=> model.CategoryName).ToHtmlString()))
        <div class="editor-label">
            @Html.LabelFor(model => model.Description)
        <div class="editor-field">
            @Html.EditorFor(model => model.Description)
            @Html.ValidationMessageFor(model => model.Description)
            <input type="submit" value="Create" />

In the create view we should decode the plain string using HtmlDecode() method in HttpUtility object and also use Html helper Raw to return HtmlString. 

If there any a validation error you can show using ValidationMessageFor, it will display a message along with the image.

MVC Validation example:

validation message contains images

Post your comments / questions