ASP.Net MVC: How to customize validation message showing

13,456

Solution 1

Updated Code:

View:

@model HelloWorldMvcApp.MainViewModel
@{
    Layout = null;
}

<!-- JS includes -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>


<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>


@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
    <div>
        <table>
            <tr>
                <td>ID</td>
                <td>Name</td>
                <td>State</td>
                <td>City</td>
            </tr>
            @for (int i = 0; i < Model.Students.Count; i++)
            {
                <tr>
                    <td>
                        @*<input type="text" value="@Model.Students[i].ID" />*@
                        @Html.EditorFor(m => m.Students[i].ID)
                        @Html.ValidationMessageFor(m => m.Students[i].ID)
                    </td>

                    <td>
                        @*<input type="text" value="@Model.Students[i].Name" />*@
                        @Html.EditorFor(m => m.Students[i].Name)
                        @Html.ValidationMessageFor(m => m.Students[i].Name)
                    </td>
                    <td>
                        @Html.DropDownListFor(m => m.Students[i].StateID, new SelectList(Model.Students[i].States, "ID", "Name", Model.Students[i].StateID), "-- Select States--", new { @class = "edit-mode" })
                        @Html.ValidationMessageFor(m => m.Students[i].StateID)
                    </td>
                    <td>
                        @Html.DropDownListFor(m => m.Students[i].CityID, new SelectList(Model.Students[i].Cities, "ID", "Name", Model.Students[i].CityID), "--Select States--", new { @class = "edit-model" })
                        @Html.ValidationMessageFor(m => m.Students[i].CityID)
                    </td>
                </tr>
            }
        </table>
    </div>
    <p><input type="submit" value="Submit" /></p>
}


<script>
    $(document).ready(function () {
        $("form").on("submit",function(){
            if ($("span[class='field-validation-error']").length != 0)
                $("span[class='field-validation-error']").each(function () {
                    $(this).addClass("hidden");//Add class hidden to hide  @@Html.ValidationMessageFor(model => model.xyz) if using bootstrap , else use css
                    var inputID = $(this).prev("input").attr("id");//get the id of the input field for which this validation prompted
                    $(this).prev("input select").css("border", "1px solid red");
                  //  $(this).prev("select").css("border", "1px solid red");
                    var validationMessage = $(this).text();//Get validation message for input filed which is prompted
                    $("#" + inputID).tooltip({ 'trigger': 'hover', 'title': validationMessage });//Trigger the tooltip now, if using bootstrap.
                });
        });
    });
</script>

Modal:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace HelloWorldMvcApp
{
    public class MainViewModel
    {
        public List<Student> Students { get; set; }
        public int SelectedState = 0;
        public int SelectedCity = 0;
    }

    public class Student
    {
        [Required]
        public int ID { get; set; }

        [Required]
        public string Name { get; set; }

        [Required]
        public int StateID { get; set; }

        [Required]
        public int CityID { get; set; }
        public List<States> States { get; set; }
        public List<Cities> Cities { get; set; }
    }

    public class States
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }

    public class Cities
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }
}

Controller:

using HelloWorldMvcApp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace HelloWorldMvcApp
{
    public class HomeController : Controller
    {
            public ActionResult Index()
            {
            MainViewModel oVm = new MainViewModel()
            {
                Students = new List<Student>() {
                    new Student
                    {
                        ID=1,
                        Name="JoyDev",
                        StateID=1,
                        CityID=1,
                        States=new List<States>()
                        {
                            new States
                            {
                                ID=1,
                                Name="WestBengal",
                            },
                            new States
                            {
                                ID=2,
                                Name="Bihar",
                            },
                            new States
                            {
                                ID=3,
                                Name="Orrisa",
                            }

                        },
                        Cities=new List<Cities>()
                        {
                            new Cities
                            {
                                ID=1,
                                Name="Alipur"
                            },
                            new Cities
                            {
                                ID=2,
                                Name="Asansol"
                            },
                            new Cities
                            {
                                ID=3,
                                Name="Andul"
                            }

                        }
                    },

//***********
                    new Student
                    {
                        ID=1,
                        Name="Mukti",
                        StateID=2,
                        CityID=1,
                        States=new List<States>()
                        {
                            new States
                            {
                                ID=1,
                                Name="WestBengal",
                            },
                            new States
                            {
                                ID=2,
                                Name="Bihar",
                            },
                            new States
                            {
                                ID=3,
                                Name="Orrisa",
                            }

                        },
                        Cities=new List<Cities>()
                        {
                            new Cities
                            {
                                ID=1,
                                Name="Janpur"
                            },
                            new Cities
                            {
                                ID=2,
                                Name="Madhubani"
                            },
                            new Cities
                            {
                                ID=3,
                                Name="Kanti"
                            }

                        }
                    },
//***********
                    new Student
                    {
                        ID=1,
                        Name="Somnath",
                        StateID=3,
                        CityID=2,
                        States=new List<States>()
                        {
                            new States
                            {
                                ID=1,
                                Name="WestBengal",
                            },
                            new States
                            {
                                ID=2,
                                Name="Bihar",
                            },
                            new States
                            {
                                ID=3,
                                Name="Orrisa",
                            }

                        },
                        Cities=new List<Cities>()
                        {
                            new Cities
                            {
                                ID=1,
                                Name="Chandapur"
                            },
                            new Cities
                            {
                                ID=2,
                                Name="Dhankauda"
                            },
                            new Cities
                            {
                                ID=3,
                                Name="Konarak"
                            }

                        }
                    }


                }

            };


            return View(oVm);
        }

    }
}

Below code I have tested and working.

 $("span[class='field-validation-error']").each(function () {

            $(this).addClass("hidden");//Add class hidden to hide  @@Html.ValidationMessageFor(model => model.xyz) if using bootstrap , else use css
            var inputID = $(this).attr("data-valmsg-for");//get the id of the input field for which this validation prompted
            var validationMessage = $(this).html();//Get validation message for input filed which is prompted          
            $("#" + inputID).tooltip({ 'trigger': 'hover', 'title': validationMessage });//Trigger the tooltip now, if using bootstrap.

                      //******OR*******

            $("#" + inputID).attr("tooltip",validationMessage);
              });

To understand the above code see:

  @Html.LabelFor(model => model.DestinationPhoneNmber, new { @class = "control-label" })
                    @Html.TextBoxFor(model => model.DestinationPhoneNmber, new { @class = "form-control", @id = "DestinationPhoneNmber", @placeholder = "+919876543210" })
                    @Html.ValidationMessageFor(model => model.DestinationPhoneNmber)

Genrates

            <label class="control-label" for="DestinationPhoneNmber">Destination Phone Number*</label>
            <input class="input-validation-error form-control" data-val="true" data-val-required="Please enter the destination phone number!" id="DestinationPhoneNmber" name="DestinationPhoneNmber" placeholder="+919876543210" type="text" value="">
            <span class="field-validation-error" data-valmsg-for="DestinationPhoneNmber" data-valmsg-replace="true">Please enter the destination phone number!</span>

The id given in the above input field as DestinationPhoneNmber is though not required as if we do not assign any id in the input filed it takes modal property name as its id by default.

Solution 2

Instead of [Required] try [Required (ErrorMessage = "Please add something!" )]

Share:
13,456
Mou
Author by

Mou

my friends are id http://stackoverflow.com/users/508127/thomas http://stackoverflow.com/users/6188148/monojit-sarkar

Updated on June 30, 2022

Comments

  • Mou
    Mou almost 2 years

    below is the code where i generate a html table in for loop and bind textbox & dropdown. also use jquery unobtrusive library to validate textbox & dropdown.

    all working but i want to customize validation bit different way.in my case validation messages are showing but i want validation message will not show rather when user place mouse cursor on red border textbox or red border dropdown then validation message will display as a tool tip.

    how can i attach validation message to title attribute of textbox and dropdown ?

    here is my full code. please see and come with suggestion or rectified sample like what to add or change in my existing code to achieve what i want.

    Model and view model

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Web;
    
    namespace RemoveValidateMessage.Models
    {
        public class MainViewModel
        {
            public List<Student> Students { get; set; }
            public int SelectedState = 0;
            public int SelectedCity = 0;
        }
    
        public class Student
        {
            [Required]
            public int ID { get; set; }
    
            [Required]
            public string Name { get; set; }
    
            [Required]
            public int StateID { get; set; }
    
            [Required]
            public int CityID { get; set; }
            public List<States> States { get; set; }
            public List<Cities> Cities { get; set; }
        }
    
        public class States
        {
            public int ID { get; set; }
            public string Name { get; set; }
        }
    
        public class Cities
        {
            public int ID { get; set; }
            public string Name { get; set; }
        }
    }
    

    Controllers

    using RemoveValidateMessage.Models;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace RemoveValidateMessage.Controllers
    {
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
                MainViewModel oVm = new MainViewModel()
                {
                    Students = new List<Student>() {
                        new Student
                        {
                            ID=1,
                            Name="JoyDev",
                            StateID=1,
                            CityID=1,
                            States=new List<States>()
                            {
                                new States
                                {
                                    ID=1,
                                    Name="WestBengal",
                                },
                                new States
                                {
                                    ID=2,
                                    Name="Bihar",
                                },
                                new States
                                {
                                    ID=3,
                                    Name="Orrisa",
                                }
    
                            },
                            Cities=new List<Cities>()
                            {
                                new Cities
                                {
                                    ID=1,
                                    Name="Alipur"
                                },
                                new Cities
                                {
                                    ID=2,
                                    Name="Asansol"
                                },
                                new Cities
                                {
                                    ID=3,
                                    Name="Andul"
                                }
    
                            }
                        },
    
    //***********
                        new Student
                        {
                            ID=1,
                            Name="Mukti",
                            StateID=2,
                            CityID=1,
                            States=new List<States>()
                            {
                                new States
                                {
                                    ID=1,
                                    Name="WestBengal",
                                },
                                new States
                                {
                                    ID=2,
                                    Name="Bihar",
                                },
                                new States
                                {
                                    ID=3,
                                    Name="Orrisa",
                                }
    
                            },
                            Cities=new List<Cities>()
                            {
                                new Cities
                                {
                                    ID=1,
                                    Name="Janpur"
                                },
                                new Cities
                                {
                                    ID=2,
                                    Name="Madhubani"
                                },
                                new Cities
                                {
                                    ID=3,
                                    Name="Kanti"
                                }
    
                            }
                        },
    //***********
                        new Student
                        {
                            ID=1,
                            Name="Somnath",
                            StateID=3,
                            CityID=2,
                            States=new List<States>()
                            {
                                new States
                                {
                                    ID=1,
                                    Name="WestBengal",
                                },
                                new States
                                {
                                    ID=2,
                                    Name="Bihar",
                                },
                                new States
                                {
                                    ID=3,
                                    Name="Orrisa",
                                }
    
                            },
                            Cities=new List<Cities>()
                            {
                                new Cities
                                {
                                    ID=1,
                                    Name="Chandapur"
                                },
                                new Cities
                                {
                                    ID=2,
                                    Name="Dhankauda"
                                },
                                new Cities
                                {
                                    ID=3,
                                    Name="Konarak"
                                }
    
                            }
                        }
    
    
                    }
    
                };
    
    
                return View(oVm);
            }
    
            [HttpPost]
            public ActionResult Index(MainViewModel model)
            {
                //if (ModelState.IsValid)
                //{
                //    return View(model);
                //}
                for (int i = 0; i < model.Students.Count;i++ )
                {
                    model.Students[i].States = new List<States>()
                            {
                                new States
                                {
                                    ID=1,
                                    Name="WestBengal",
                                },
                                new States
                                {
                                    ID=2,
                                    Name="Bihar",
                                },
                                new States
                                {
                                    ID=3,
                                    Name="Orrisa",
                                }
    
                            };
                    model.Students[i].Cities = new List<Cities>()
                            {
                                new Cities
                                {
                                    ID=1,
                                    Name="Chandapur"
                                },
                                new Cities
                                {
                                    ID=2,
                                    Name="Dhankauda"
                                },
                                new Cities
                                {
                                    ID=3,
                                    Name="Konarak"
                                }
    
                            };
                }
                return View(model);
            }
            public ActionResult Test()
            {
                ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
                ViewBag.Time = DateTime.Now.ToString();
                return View();
            }
    
    
            public ActionResult About()
            {
                ViewBag.Message = "Your app description page.";
    
                return View();
            }
    
            public ActionResult Contact()
            {
                ViewBag.Message = "Your contact page.";
    
                return View();
            }
        }
    }
    

    View Code

    <script src="~/Scripts/jquery-1.8.2.min.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
    
    @model RemoveValidateMessage.Models.MainViewModel
    @{
        ViewBag.Title = "Home Page";
    }
    
    @using (Html.BeginForm("Index", "Home",FormMethod.Post))
    { 
    <div>
        <table>
            <tr>
                <td>ID</td>
                <td>Name</td>
                <td>State</td>
                <td>City</td>
            </tr>
            @for (int i = 0; i < Model.Students.Count; i++)
            {
                <tr>
                    <td>
                        @*<input type="text" value="@Model.Students[i].ID" />*@
                    @Html.EditorFor(m=>m.Students[i].ID)
                    @Html.ValidationMessageFor(m => m.Students[i].ID)
                    </td>
    
                    <td>
                    @*<input type="text" value="@Model.Students[i].Name" />*@
                        @Html.EditorFor(m => m.Students[i].Name)
                        @Html.ValidationMessageFor(m => m.Students[i].Name)
                    </td>
                    <td>
                        @Html.DropDownListFor(m => m.Students[i].StateID, new SelectList(Model.Students[i].States, "ID", "Name", Model.Students[i].StateID), "-- Select States--", new { @class = "edit-mode" })
                        @Html.ValidationMessageFor(m => m.Students[i].StateID)
                    </td>
                    <td>
                       @Html.DropDownListFor(m => m.Students[i].CityID, new SelectList(Model.Students[i].Cities, "ID", "Name", Model.Students[i].CityID), "--Select States--", new { @class = "edit-model" })
                        @Html.ValidationMessageFor(m => m.Students[i].CityID)
                    </td>
                </tr>
            }
        </table>
    </div>
     <p><input type="submit" value="Submit" /></p>
    }
    

    Screen shot

    enter image description here

  • Mou
    Mou over 8 years
    i like to know how to add error message to title attribute with right controls ?
  • Mou
    Mou over 8 years
    if i do it then this message will be show "Please add something" but i want do not want to show validation message rather i want to attach validation message with html control. suppose first name textbox is empty in 2nd row. so i when validation will fire then first name textbox in 2nd row will have red border and when user place mouse on that textbox then validation message will be shown in tooltip. tooltip means title attribute.
  • Ellis Shen
    Ellis Shen over 8 years
    @Mou you can put html mark up in, which you can style up how you want. It'd be cleaner to extend RequiredAttribute than keep doing that on each attribute.
  • Mou
    Mou over 8 years
    which thing u r hiding $(this).addClass("hidden") this code objective not clear ?
  • Anil  Panwar
    Anil Panwar over 8 years
    I was hiding html generated from @Html.ValidationMessageFor(model => model.xyz) using bootstrap class, but as you are not using bootstrap you have to use css to hide it.
  • Anil  Panwar
    Anil Panwar over 8 years
    @Html.ValidationMessageFor(model => model.xyz) generate <span class="field-validation-error" data-valmsg-for="" data-valmsg-replace="true">Valiation message</span>
  • Mou
    Mou over 8 years
    here u paste html code for validation message where data-valmsg-for="" but in your above code u r reading var inputID = $(this).attr("data-valmsg-for") data-valmsg-for="" is empty then what will be stored in inputID ?
  • Anil  Panwar
    Anil Panwar over 8 years
    $(this) is current span, as we are using each span having class field-validation-error, and data-valmsg-for="" stores the id of the input field. If @Html.TextBoxFor(model => model.xyz) is my input field then its id will be xyz by default.
  • Mou
    Mou over 8 years
    i just asked if this data-valmsg-for is empty then how could get input id from this attribute ? var inputID = $(this).attr("data-valmsg-for") when something will be stored in data-valmsg-for ? when validation will be fail then corresponding control's id will be stored in data-valmsg-for ??
  • Anil  Panwar
    Anil Panwar over 8 years
    It will never be null, data-annotation add it automatically, data-valmsg-for="Model property name by default same as the name of modal property"
  • Mou
    Mou over 8 years
    hey see this link where u will see code dotnetfiddle.net/30YQEX i used your code to attach validation message to title attribute of control but not working
  • Anil  Panwar
    Anil Panwar over 8 years
    Script you wrote is not inside the $(document).ready(function(){ // put here script });
  • Mou
    Mou over 8 years
    i put your script in side document.ready but still not working.
  • Anil  Panwar
    Anil Panwar over 8 years
    You script is not running in that fiddle , try putting the alert inside the for each loop for debugging.