In this article you will learn the followings things:

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. namespace ValidationSummary.Models
  7. {
  8. public class MemberModel
  9. {
  10. [Display(Name ="Member Name")]
  11. [Required(ErrorMessage ="Member Name is required.")]
  12. public string MemberName { get; set; }
  13. [Display(Name ="Mobile Number")]
  14. [Required(ErrorMessage ="Mobile Number is required.") ]
  15. [StringLength(10,MinimumLength = 10, ErrorMessage ="Minimum and Maximum 10 Diigit Required.")]
  16. public string Mobile { get; set; }
  17. [Required(ErrorMessage ="City is required.")]
  18. public string City { get; set; }
  19. }
  20. }
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,
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. ViewBag.Title = "Create";
  4. }
  5. <h2>Create</h2>
  6. @using (Html.BeginForm())
  7. {
  8. @Html.AntiForgeryToken()
  9. <div class="form-horizontal">
  10. <h4>MemberModel</h4>
  11. <hr />
  12. @Html.ValidationSummary(true, "", new { @class = "text-danger" })
  13. <div class="form-group">
  14. @Html.LabelFor(model => model.MemberName, htmlAttributes: new { @class = "control-label col-md-2" })
  15. <div class="col-md-10">
  16. @Html.EditorFor(model => model.MemberName, new { htmlAttributes = new { @class = "form-control" } })
  17. @Html.ValidationMessageFor(model => model.MemberName, "", new { @class = "text-danger" })
  18. </div>
  19. </div>
  20. <div class="form-group">
  21. @Html.LabelFor(model => model.Mobile, htmlAttributes: new { @class = "control-label col-md-2" })
  22. <div class="col-md-10">
  23. @Html.EditorFor(model => model.Mobile, new { htmlAttributes = new { @class = "form-control" } })
  24. @Html.ValidationMessageFor(model => model.Mobile, "", new { @class = "text-danger" })
  25. </div>
  26. </div>
  27. <div class="form-group">
  28. @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })
  29. <div class="col-md-10">
  30. @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })
  31. @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
  32. </div>
  33. </div>
  34. <div class="form-group">
  35. <div class="col-md-offset-2 col-md-10">
  36. <input type="submit" value="Create" class="btn btn-default" />
  37. </div>
  38. </div>
  39. </div>
  40. }
  41. <div>
  42. @Html.ActionLink("Back to List", "Index")
  43. </div>
  44. <script src="~/Scripts/jquery-1.10.2.min.js"></script>
  45. <script src="~/Scripts/jquery.validate.min.js"></script>
  46. <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. namespace ValidationSummary
  8. {
  9. public class RouteConfig
  10. {
  11. public static void RegisterRoutes(RouteCollection routes)
  12. {
  13. routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
  14. routes.MapRoute(
  15. name: "Default",
  16. url: "{controller}/{action}/{id}",
  17. defaults: new { controller = "Member", action = "Create", id = UrlParameter.Optional }
  18. );
  19. }
  20. }
  21. }

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. namespace ValidationSummary.Controllers
  7. {
  8. public class MemberController : Controller
  9. {
  10. // GET: Member
  11. public ActionResult Index()
  12. {
  13. return View();
  14. }
  15. // GET: Member/Details/5
  16. public ActionResult Details(int id)
  17. {
  18. return View();
  19. }
  20. // GET: Member/Create
  21. public ActionResult Create()
  22. {
  23. return View();
  24. }
  25. // POST: Member/Create
  26. [HttpPost]
  27. public ActionResult Create(FormCollection collection)
  28. {
  29. try
  30. {
  31. // TODO: Add insert logic here
  32. return RedirectToAction("Index");
  33. }
  34. catch
  35. {
  36. return View();
  37. }
  38. }
  39. // GET: Member/Edit/5
  40. public ActionResult Edit(int id)
  41. {
  42. return View();
  43. }
  44. // POST: Member/Edit/5
  45. [HttpPost]
  46. public ActionResult Edit(int id, FormCollection collection)
  47. {
  48. try
  49. {
  50. // TODO: Add update logic here
  51. return RedirectToAction("Index");
  52. }
  53. catch
  54. {
  55. return View();
  56. }
  57. }
  58. // GET: Member/Delete/5
  59. public ActionResult Delete(int id)
  60. {
  61. return View();
  62. }
  63. // POST: Member/Delete/5
  64. [HttpPost]
  65. public ActionResult Delete(int id, FormCollection collection)
  66. {
  67. try
  68. {
  69. // TODO: Add delete logic here
  70. return RedirectToAction("Index");
  71. }
  72. catch
  73. {
  74. return View();
  75. }
  76. }
  77. }
  78. }
Create.cshtml code
  1. @model ValidationSummary.Models.MemberModel
  2. @{
  3. ViewBag.Title = "Create";
  4. }
  5. <style>
  6. .error {
  7. color: red;
  8. }
  9. </style>
  10. <h2>Create</h2>
  11. @using (Html.BeginForm())
  12. {
  13. @Html.AntiForgeryToken()
  14. <div class="form-horizontal">
  15. <h4>MemberModel</h4>
  16. <hr />
  17. @Html.ValidationSummary(true, "", new { @class = "text-danger" })
  18. <div class="form-group">
  19. @Html.LabelFor(model => model.MemberName, htmlAttributes: new { @class = "control-label col-md-2" })
  20. <div class="col-md-10">
  21. @Html.EditorFor(model => model.MemberName, new { htmlAttributes = new { @class = "form-control" } })
  22. @Html.ValidationMessageFor(model => model.MemberName, "", new { @class = "text-danger" })
  23. </div>
  24. </div>
  25. <div class="form-group">
  26. @Html.LabelFor(model => model.Mobile, htmlAttributes: new { @class = "control-label col-md-2" })
  27. <div class="col-md-10">
  28. @Html.EditorFor(model => model.Mobile, new { htmlAttributes = new { @class = "form-control" } })
  29. @Html.ValidationMessageFor(model => model.Mobile, "", new { @class = "text-danger" })
  30. </div>
  31. </div>
  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. <div class="form-group">
  40. <div class="col-md-offset-2 col-md-10">
  41. <input type="submit" value="Create" class="btn btn-default" />
  42. </div>
  43. </div>
  44. </div>
  45. @Html.ValidationSummary(false, "", new { @class = "error" })
  46. }
  47. <div>
  48. @Html.ActionLink("Back to List", "Index")
  49. </div>
  50. <script src="~/Scripts/jquery-1.10.2.min.js"></script>
  51. <script src="~/Scripts/jquery.validate.min.js"></script>
  52. <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. namespace ValidationSummary.Models
  7. {
  8. public class MemberModel
  9. {
  10. [Display(Name ="Member Name")]
  11. [Required(ErrorMessage ="Member Name is required.")]
  12. public string MemberName { get; set; }
  13. [Display(Name ="Mobile Number")]
  14. [Required(ErrorMessage ="Mobile Number is required.") ]
  15. [StringLength(10,MinimumLength = 10, ErrorMessage ="Minimum and Maximum 10 Diigit Required.")]
  16. public string Mobile { get; set; }
  17. [Required(ErrorMessage ="City is required.")]
  18. public string City { get; set; }
  19. }
  20. }
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. namespace ValidationSummary
  8. {
  9. public class RouteConfig
  10. {
  11. public static void RegisterRoutes(RouteCollection routes)
  12. {
  13. routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
  14. routes.MapRoute(
  15. name: "Default",
  16. url: "{controller}/{action}/{id}",
  17. defaults: new { controller = "Member", action = "Create", id = UrlParameter.Optional }
  18. );
  19. }
  20. }
  21. }
Happy Coding.