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”
In the above screenshot select the following:
- Empty -- Template
- MVC -- Add Folder and core references for
- No Authentication : Authentication
Creating project.
Solution Explorer default view,
Now right click on MODEL folder. Select ADD-->CLASS
Type file name “MemberModel”
To use [Required] and [Display] attribute the required namespace is “System.ComponentModel.DataAnnotations”
MemberModel.cs code
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.Linq;
- using System.Web;
-
- namespace ValidationSummary.Models
- {
- public class MemberModel
- {
- [Display(Name ="Member Name")]
- [Required(ErrorMessage ="Member Name is required.")]
- public string MemberName { get; set; }
-
- [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; }
-
- [Required(ErrorMessage ="City is required.")]
- public string City { get; set; }
- }
- }
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
Now select MVC5 Controller with read/write actions item
Click ADD button, and the below ADD Controller dialog box will appear. Create Controller named “MemberController”.
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.
The following code is generated through scaffolding. . .
Create.cshtml code
- @model ValidationSummary.Models.MemberModel
-
- @{
- ViewBag.Title = "Create";
- }
-
- <h2>Create</h2>
-
- @using (Html.BeginForm())
- {
- @Html.AntiForgeryToken()
- <div class="form-horizontal">
- <h4>MemberModel</h4>
- <hr />
- @Html.ValidationSummary(true, "", new { @class = "text-danger" })
- <div class="form-group">
- @Html.LabelFor(model => model.MemberName, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.MemberName, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.MemberName, "", new { @class = "text-danger" })
- </div>
- </div>
-
- <div class="form-group">
- @Html.LabelFor(model => model.Mobile, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.Mobile, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.Mobile, "", new { @class = "text-danger" })
- </div>
- </div>
-
- <div class="form-group">
- @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
- </div>
- </div>
-
- <div class="form-group">
- <div class="col-md-offset-2 col-md-10">
- <input type="submit" value="Create" class="btn btn-default" />
- </div>
- </div>
- </div>
- }
-
- <div>
- @Html.ActionLink("Back to List", "Index")
- </div>
-
- <script src="~/Scripts/jquery-1.10.2.min.js"></script>
- <script src="~/Scripts/jquery.validate.min.js"></script>
- <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
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using System.Web.Routing;
-
- namespace ValidationSummary
- {
- public class RouteConfig
- {
- public static void RegisterRoutes(RouteCollection routes)
- {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
-
- routes.MapRoute(
- name: "Default",
- url: "{controller}/{action}/{id}",
- defaults: new { controller = "Member", action = "Create", id = UrlParameter.Optional }
- );
- }
- }
- }
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
Now I clicked CREATE button without entering anything.
If I enter only 5 characters in Mobile Number field and press CREATE button, then Mobile Number field displays this error message.
Now we are going to create Validation Summary.
At last in view add the following line for receiving the validation summary.
- @Html.ValidationSummary(false, "", new { @class = "error" })
Add style tag at the beginning.
- <style>
- .error {
- color: red;
- }
- </style>
OUTPUT
Full Source Code
MemberController.cs code,
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
-
- namespace ValidationSummary.Controllers
- {
- public class MemberController : Controller
- {
-
- public ActionResult Index()
- {
- return View();
- }
-
-
- public ActionResult Details(int id)
- {
- return View();
- }
-
-
- public ActionResult Create()
- {
- return View();
- }
-
-
- [HttpPost]
- public ActionResult Create(FormCollection collection)
- {
- try
- {
-
-
- return RedirectToAction("Index");
- }
- catch
- {
- return View();
- }
- }
-
-
- public ActionResult Edit(int id)
- {
- return View();
- }
-
-
- [HttpPost]
- public ActionResult Edit(int id, FormCollection collection)
- {
- try
- {
-
-
- return RedirectToAction("Index");
- }
- catch
- {
- return View();
- }
- }
-
-
- public ActionResult Delete(int id)
- {
- return View();
- }
-
-
- [HttpPost]
- public ActionResult Delete(int id, FormCollection collection)
- {
- try
- {
-
-
- return RedirectToAction("Index");
- }
- catch
- {
- return View();
- }
- }
- }
- }
Create.cshtml code
- @model ValidationSummary.Models.MemberModel
-
- @{
- ViewBag.Title = "Create";
- }
- <style>
- .error {
- color: red;
- }
- </style>
- <h2>Create</h2>
-
- @using (Html.BeginForm())
- {
- @Html.AntiForgeryToken()
-
- <div class="form-horizontal">
- <h4>MemberModel</h4>
- <hr />
- @Html.ValidationSummary(true, "", new { @class = "text-danger" })
- <div class="form-group">
- @Html.LabelFor(model => model.MemberName, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.MemberName, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.MemberName, "", new { @class = "text-danger" })
- </div>
- </div>
-
- <div class="form-group">
- @Html.LabelFor(model => model.Mobile, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.Mobile, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.Mobile, "", new { @class = "text-danger" })
- </div>
- </div>
-
- <div class="form-group">
- @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
- </div>
- </div>
-
- <div class="form-group">
- <div class="col-md-offset-2 col-md-10">
- <input type="submit" value="Create" class="btn btn-default" />
- </div>
- </div>
- </div>
- @Html.ValidationSummary(false, "", new { @class = "error" })
- }
-
- <div>
- @Html.ActionLink("Back to List", "Index")
- </div>
-
- <script src="~/Scripts/jquery-1.10.2.min.js"></script>
- <script src="~/Scripts/jquery.validate.min.js"></script>
- <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
MemberModel.cs code
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.Linq;
- using System.Web;
-
- namespace ValidationSummary.Models
- {
- public class MemberModel
- {
- [Display(Name ="Member Name")]
- [Required(ErrorMessage ="Member Name is required.")]
- public string MemberName { get; set; }
-
- [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; }
-
- [Required(ErrorMessage ="City is required.")]
- public string City { get; set; }
- }
- }
RouteConfig.cs code
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using System.Web.Routing;
-
- namespace ValidationSummary
- {
- public class RouteConfig
- {
- public static void RegisterRoutes(RouteCollection routes)
- {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
-
- routes.MapRoute(
- name: "Default",
- url: "{controller}/{action}/{id}",
- defaults: new { controller = "Member", action = "Create", id = UrlParameter.Optional }
- );
- }
- }
- }
Happy Coding.