Learn About Validation Message And Validation Summary In ASP.NET MVC

In this article you will learn the followings things:
  • How to set validation message
  • How to set validation summary
  • What are data annotations?
  • Types of data annotations

Validation

 
Validation means the action of checking or proving the validity or accuracy of something.
 
Validation is used for accepting the correct data from users.  Sometimes, a user will intentionally or by mistake enter the wrong data. By using validation on all inputs we can easily restrict incorrect entry submission.
 
Validation Summary
 
The summary displays all of the errors in one place.
 

What is Data Annotation?

 
Data annotation means writing annotations (note/title) on Model Property. By using data annotation we can easily put validation on view.
 

Types of Data-Annotations

 
Various types of data annotation
 
DATA-ANNOTATIONS
DESCRIPTION
Required
Compulsory data required.
DisplayName
Display text you want to display on form.
StringLength
Set Maximum length for a string property.
Range
Set Minimum , Maximum value for numeric field.
Bind
Exclude or Include property for validation.
ScaffoldColumn
Hide or Unhide property while generating forms.
 
For more details visit the following links,
  • https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/models-data/validation-with-the-data-annotation-validators-cs
  • https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions/mvc-music-store/mvc-music-store-part-6
Create a project called “ValidationSummary”
 
Learn About Validation Message And Validation Summary In ASP.NET MVC
 
Learn About Validation Message And Validation Summary In ASP.NET MVC
 
In the above screenshot select the following:
  1. Empty -- Template
  2. MVC -- Add Folder and core references for
  3. No Authentication : Authentication
Learn About Validation Message And Validation Summary In ASP.NET MVC
 
Creating project.
 
Solution Explorer default view,
 
Learn About Validation Message And Validation Summary In ASP.NET MVC
 
Now right click on MODEL folder. Select ADD-->CLASS
 
Learn About Validation Message And Validation Summary In ASP.NET MVC
 
Type file name “MemberModel”
 
Learn About Validation Message And Validation Summary In ASP.NET MVC
 
To use [Required] and [Display] attribute the required namespace is “System.ComponentModel.DataAnnotations”
 
Learn About Validation Message And Validation Summary In ASP.NET MVC
 
MemberModel.cs code
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4. using System.Linq;  
  5. using System.Web;  
  6.   
  7. namespace ValidationSummary.Models  
  8. {  
  9.     public class MemberModel  
  10.     {  
  11.         [Display(Name ="Member Name")]  
  12.         [Required(ErrorMessage ="Member Name is required.")]  
  13.         public string MemberName { getset; }  
  14.   
  15.         [Display(Name ="Mobile Number")]  
  16.         [Required(ErrorMessage ="Mobile Number is required.") ]  
  17.         [StringLength(10,MinimumLength = 10, ErrorMessage ="Minimum and Maximum 10 Diigit Required.")]  
  18.         public string Mobile { getset; }  
  19.   
  20.         [Required(ErrorMessage ="City is required.")]  
  21.         public string City { getset; }  
  22.     }  
  23. }  
Above code Explanation: MEMBERMODEL.CS
 
SR.
NO.
PROPERTY
DESCRIPTION
1
[Display(Name ="Member Name")]
[Required(ErrorMessage="Member Name is required.")]
public string MemberName { get; set; }
While you generate CREATE/EDIT/DELETE view
DISPLAY:  Title of TextBox will get MemberName.
REQUIRED: User can not leave this field blank;  if user doesn't fill it in then he will get error message.
2
[Display(Name ="Mobile Number")]
[Required(ErrorMessage="Mobile Number is required.") ]
[StringLength(10,MinimumLength = 10, ErrorMessage ="Minimum and Maximum 10 Diigit Required.")]
public string Mobile { get; set; }
DISPLAY:  Title of TextBox will get Mobile Number.
REQUIRED: User can not leave this field blank; if user doesn't fill it in then he will get error message.
STRING LENGTH: User should enter 10 digit minimum.
3
[Required(ErrorMessage ="City is required.")]
public string City { get; set; }
 
 
Now right click on CONTROLLER folder select ADD-->CONTROLLER
 
Learn About Validation Message And Validation Summary In ASP.NET MVC 
 
Now select MVC5 Controller with read/write actions item
 
Learn About Validation Message And Validation Summary In ASP.NET MVC 
 
Click ADD button, and the below ADD Controller dialog box will appear. Create Controller named “MemberController”.
 
Learn About Validation Message And Validation Summary In ASP.NET MVC 
 
Now you can see in MemberController.cs file there are the following ActionMethods,
  • Index
  • Details
  • Create
  • Edit
  • Delete
But we are going to use only CREATE action method.
 
Now we are going to create view for CREATE ActionMethod.
 
Right click inside CREATE ActionMethod.
 
Learn About Validation Message And Validation Summary In ASP.NET MVC
 
Learn About Validation Message And Validation Summary In ASP.NET MVC
 
Learn About Validation Message And Validation Summary In ASP.NET MVC 
 
The following code is generated through scaffolding. . .
 
Create.cshtml code
  1. @model ValidationSummary.Models.MemberModel  
  2.   
  3. @{  
  4.     ViewBag.Title = "Create";  
  5. }  
  6.   
  7. <h2>Create</h2>  
  8.   
  9. @using (Html.BeginForm())   
  10. {  
  11.     @Html.AntiForgeryToken()  
  12.     <div class="form-horizontal">  
  13.         <h4>MemberModel</h4>  
  14.         <hr />  
  15.         @Html.ValidationSummary(true""new { @class = "text-danger" })  
  16.         <div class="form-group">  
  17.             @Html.LabelFor(model => model.MemberName, htmlAttributes: new { @class = "control-label col-md-2" })  
  18.             <div class="col-md-10">  
  19.                 @Html.EditorFor(model => model.MemberName, new { htmlAttributes = new { @class = "form-control" } })  
  20.                 @Html.ValidationMessageFor(model => model.MemberName, ""new { @class = "text-danger" })  
  21.             </div>  
  22.         </div>  
  23.   
  24.         <div class="form-group">  
  25.             @Html.LabelFor(model => model.Mobile, htmlAttributes: new { @class = "control-label col-md-2" })  
  26.             <div class="col-md-10">  
  27.                 @Html.EditorFor(model => model.Mobile, new { htmlAttributes = new { @class = "form-control" } })  
  28.                 @Html.ValidationMessageFor(model => model.Mobile, ""new { @class = "text-danger" })  
  29.             </div>  
  30.         </div>  
  31.   
  32.         <div class="form-group">  
  33.             @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })  
  34.             <div class="col-md-10">  
  35.                 @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })  
  36.                 @Html.ValidationMessageFor(model => model.City, ""new { @class = "text-danger" })  
  37.             </div>  
  38.         </div>  
  39.   
  40.         <div class="form-group">  
  41.             <div class="col-md-offset-2 col-md-10">  
  42.                 <input type="submit" value="Create" class="btn btn-default" />  
  43.             </div>  
  44.         </div>  
  45.     </div>  
  46. }  
  47.   
  48. <div>  
  49.     @Html.ActionLink("Back to List""Index")  
  50. </div>  
  51.   
  52. <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
  53. <script src="~/Scripts/jquery.validate.min.js"></script>  
  54. <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>  
Now double click on RouteConfig.cs which is inside APP_START folder in root.
 
Update your RouteConfig.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using System.Web.Routing;  
  7.   
  8. namespace ValidationSummary  
  9. {  
  10.     public class RouteConfig  
  11.     {  
  12.         public static void RegisterRoutes(RouteCollection routes)  
  13.         {  
  14.             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  15.   
  16.             routes.MapRoute(  
  17.                 name: "Default",  
  18.                 url: "{controller}/{action}/{id}",  
  19.                 defaults: new { controller = "Member", action = "Create", id = UrlParameter.Optional }  
  20.             );  
  21.         }  
  22.     }  
  23. }  

Why did we update RouteConfig.cs?

 
We want Create ActionMethod of MemberController to execute by default.
 
Now hit F5 to execute the project.
 
Output
 
Normal View
 
Learn About Validation Message And Validation Summary In ASP.NET MVC 
 
Now I clicked CREATE button without entering anything.
 
Learn About Validation Message And Validation Summary In ASP.NET MVC 
 
If I enter only 5 characters in Mobile Number field and press CREATE button, then Mobile Number field displays this error message.
 
Learn About Validation Message And Validation Summary In ASP.NET MVC 
 
Now we are going to create Validation Summary.
 
At last in view add the following line for  receiving the validation summary.
  1. @Html.ValidationSummary(false""new { @class = "error" })  
Add style tag at the beginning.
  1. <style>  
  2. .error {  
  3.             color: red;  
  4.         }  
  5. </style>  
OUTPUT
 
Learn About Validation Message And Validation Summary In ASP.NET MVC 
 
Full Source Code
 
MemberController.cs code,
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.   
  7. namespace ValidationSummary.Controllers  
  8. {  
  9.     public class MemberController : Controller  
  10.     {  
  11.         // GET: Member  
  12.         public ActionResult Index()  
  13.         {  
  14.             return View();  
  15.         }  
  16.   
  17.         // GET: Member/Details/5  
  18.         public ActionResult Details(int id)  
  19.         {  
  20.             return View();  
  21.         }  
  22.   
  23.         // GET: Member/Create  
  24.         public ActionResult Create()  
  25.         {  
  26.             return View();  
  27.         }  
  28.   
  29.         // POST: Member/Create  
  30.         [HttpPost]  
  31.         public ActionResult Create(FormCollection collection)  
  32.         {  
  33.             try  
  34.             {  
  35.                 // TODO: Add insert logic here  
  36.   
  37.                 return RedirectToAction("Index");  
  38.             }  
  39.             catch  
  40.             {  
  41.                 return View();  
  42.             }  
  43.         }  
  44.   
  45.         // GET: Member/Edit/5  
  46.         public ActionResult Edit(int id)  
  47.         {  
  48.             return View();  
  49.         }  
  50.   
  51.         // POST: Member/Edit/5  
  52.         [HttpPost]  
  53.         public ActionResult Edit(int id, FormCollection collection)  
  54.         {  
  55.             try  
  56.             {  
  57.                 // TODO: Add update logic here  
  58.   
  59.                 return RedirectToAction("Index");  
  60.             }  
  61.             catch  
  62.             {  
  63.                 return View();  
  64.             }  
  65.         }  
  66.   
  67.         // GET: Member/Delete/5  
  68.         public ActionResult Delete(int id)  
  69.         {  
  70.             return View();  
  71.         }  
  72.   
  73.         // POST: Member/Delete/5  
  74.         [HttpPost]  
  75.         public ActionResult Delete(int id, FormCollection collection)  
  76.         {  
  77.             try  
  78.             {  
  79.                 // TODO: Add delete logic here  
  80.   
  81.                 return RedirectToAction("Index");  
  82.             }  
  83.             catch  
  84.             {  
  85.                 return View();  
  86.             }  
  87.         }  
  88.     }  
  89. }  
Create.cshtml code
  1. @model ValidationSummary.Models.MemberModel  
  2.   
  3. @{  
  4.     ViewBag.Title = "Create";  
  5. }  
  6. <style>  
  7. .error {  
  8.             color: red;  
  9.         }  
  10. </style>  
  11. <h2>Create</h2>  
  12.   
  13. @using (Html.BeginForm())   
  14. {  
  15.     @Html.AntiForgeryToken()  
  16.       
  17.     <div class="form-horizontal">  
  18.         <h4>MemberModel</h4>  
  19.         <hr />  
  20.         @Html.ValidationSummary(true""new { @class = "text-danger" })  
  21.         <div class="form-group">  
  22.             @Html.LabelFor(model => model.MemberName, htmlAttributes: new { @class = "control-label col-md-2" })  
  23.             <div class="col-md-10">  
  24.                 @Html.EditorFor(model => model.MemberName, new { htmlAttributes = new { @class = "form-control" } })  
  25.                 @Html.ValidationMessageFor(model => model.MemberName, ""new { @class = "text-danger" })  
  26.             </div>  
  27.         </div>  
  28.   
  29.         <div class="form-group">  
  30.             @Html.LabelFor(model => model.Mobile, htmlAttributes: new { @class = "control-label col-md-2" })  
  31.             <div class="col-md-10">  
  32.                 @Html.EditorFor(model => model.Mobile, new { htmlAttributes = new { @class = "form-control" } })  
  33.                 @Html.ValidationMessageFor(model => model.Mobile, ""new { @class = "text-danger" })  
  34.             </div>  
  35.         </div>  
  36.   
  37.         <div class="form-group">  
  38.             @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })  
  39.             <div class="col-md-10">  
  40.                 @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })  
  41.                 @Html.ValidationMessageFor(model => model.City, ""new { @class = "text-danger" })  
  42.             </div>  
  43.         </div>  
  44.   
  45.         <div class="form-group">  
  46.             <div class="col-md-offset-2 col-md-10">  
  47.                 <input type="submit" value="Create" class="btn btn-default" />  
  48.             </div>  
  49.         </div>  
  50.     </div>  
  51.     @Html.ValidationSummary(false""new { @class = "error" })  
  52. }  
  53.   
  54. <div>  
  55.     @Html.ActionLink("Back to List""Index")  
  56. </div>  
  57.   
  58. <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
  59. <script src="~/Scripts/jquery.validate.min.js"></script>  
  60. <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>  
MemberModel.cs code
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4. using System.Linq;  
  5. using System.Web;  
  6.   
  7. namespace ValidationSummary.Models  
  8. {  
  9.     public class MemberModel  
  10.     {  
  11.         [Display(Name ="Member Name")]  
  12.         [Required(ErrorMessage ="Member Name is required.")]  
  13.         public string MemberName { getset; }  
  14.   
  15.         [Display(Name ="Mobile Number")]  
  16.         [Required(ErrorMessage ="Mobile Number is required.") ]  
  17.         [StringLength(10,MinimumLength = 10, ErrorMessage ="Minimum and Maximum 10 Diigit Required.")]  
  18.         public string Mobile { getset; }  
  19.   
  20.         [Required(ErrorMessage ="City is required.")]  
  21.         public string City { getset; }  
  22.     }  
  23. }  
RouteConfig.cs code
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using System.Web.Routing;  
  7.   
  8. namespace ValidationSummary  
  9. {  
  10.     public class RouteConfig  
  11.     {  
  12.         public static void RegisterRoutes(RouteCollection routes)  
  13.         {  
  14.             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  15.   
  16.             routes.MapRoute(  
  17.                 name: "Default",  
  18.                 url: "{controller}/{action}/{id}",  
  19.                 defaults: new { controller = "Member", action = "Create", id = UrlParameter.Optional }  
  20.             );  
  21.         }  
  22.     }  
  23. }  
Happy Coding.