×

iFour Logo

Understanding Validation Tag Helpers in ASP.NET Core

Kapil Panchal - November 08, 2020

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

  • play
  • pause
  • pause
 Understanding Validation Tag Helpers in ASP.NET Core

ASP.NET core provides a validation related tag use to display a validation message to the user. To display the validation message in view the validation tag generates the Html element.

ASP.NET input tag is used to add client-side validation to input element based on data annotation defined in model. The Validation Tag helper is use to display validation message for invalid input to user. Validation Message Tag Helper (Used to displays a validation message for a single field of Model), and the Validation Summary Tag Helper (Used to displays a summary of all validation errors) are used in ASP.NET to display validation message.

Validation Tag helpers in Asp.net core


Asp.net core provides the following tag helper to display the validation message on the client-side:

  1. Validation Message Tag Helper
  2. Validation summary Tag Helper

Validation Message Tag helper


Validation Message Tag helper use element to display a validation error message for the model property specified in its attribute.

Alternative for Validation Message in HTML Helper is Html.ValidationMessageFor

Validation Summary Tag helper


Validation Summary tag helper uses the

element to display validation summary for property. Validation Summary tag helper uses an asp-validation-summary attribute to display a model validation summary on browser client.

The alternative for Validation Summary in HTML Helper is @Html.ValidationSummary

ValidationMessage : ValidationMessage is stringly typed (weakly type). A validation message is used to display a validation message if an error exists for the specified field in the Model.

ValidationMessageFor : ValidationMessageFor is indeed strongly typed. Validation Message is used to display an error if data annotations attribute specified property in the model class.

ValidationSummary : This ValidationSummary method is used to generates an unordered list (ul element) of validation messages that are in the ModelStateDictionary object.

 

Example of Validation Tag and Validation Summary:

Step-1: Create an "Asp.net core web application"

  • Open visual studio
  • Create new Asp.net web application with model-View-controller template
  • Visual studio opens your new project
create-web-app

Step-2: Add Employee Model"

Right-click on the Model folder and add Employee.cs Model

using System;
using System.ComponentModel.DataAnnotations;
namespace Demo.Models
{
public class Employee
{
[Key]
public int Id { get; set; }
[Required(ErrorMessage = "Name is required")]
public string Name { get; set; }
[Required(ErrorMessage = "Date of birth is required")]
[Display(Name = "Date of Birth")]
[DataType(DataType.Date)]
public DateTime DateofBirth { get; set; }
[Required(ErrorMessage = "Address is required")]
[StringLength(255)]
public string Address { get; set; }
[Required(ErrorMessage ="Mobile number is  required")]
[Display(Name = "Mobile Number")]
[RegularExpression(@"^(?=.*[0-9])[- .()0-9]+$", ErrorMessage ="Invalid Mobile number")]
public string Mobile { get; set; }
      
}
}
 
        

Step-3: Add Employee Controller

  • Right-click on the controller folder and add Employee controller
  • Add Employee and add Method in Employee Controller
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Demo.Models;
namespace Demo.Controllers
{
public class EmployeeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult Add()
{
return View();
}
[HttpPost]
public IActionResult Add(Employee employee)
{
if (ModelState.IsValid)
{
}
return View();
}
}
}
                
Use of ModelState.IsValid

ModelState is used to check model validation is succeeded or not.

If Model fields have definite types then it should be validated when returned to the controller. If any model field is not matched with their type then this ModelState.IsValid method returns false because these errors are defined in ModelState.

Step-4: Add View for Add Method of Employee Controller.

  • Add View for Add Method in Employee Controller.
  • Right-click on the Add Action method and "Add" View and Write following code:
 
@model Demo.Models.Employee
@{
ViewData["Title"] = "Add";
}
      

Add

Employee


 
 
@section Scripts { @{await Html.RenderPartialAsync("_ValidationScriptsPartial");} }

Validation Message Tag helper is used on Html span tag with asp-validation-for attribute


And Validation Message Tag helper generate following block of code
 

Validation Message Tag helper is used after input tag for the same field and used to display validation error message for that input.

If Server-side validation error occur then span tag body is replaced with following code:
 

 Mobile number is required 

Validation summary have following Value: ALL

ALL option displays all the validation error for model and property.
 

Above Statement generate following HTML Code:
 

Above Statement generate following HTML Code:
 

If Server-side validation error occur then tag body is replaced with following code:
 

opt-example
Model

Model option display only model level validation. This option is used to display the validation error while asp-validation-for Tag helper is used in view page.
 

The model option does not generate any HTML script.

dmodel-example
None

None option will not display any error message.
 

Step-5: Build and Run

Build and run the application

emp-add
1.6 Employee Add Page

Wants to Talk with Our Highly Skilled .Net Core Developer ? Contact now.

  How to Add Custom Error Message

A validation summary tag helper is used to display a custom error message. ModelState.AddModelError() is used to display custom error.

The ValidationSummary() method will display all the error messages added into the ModelState.

Following block of code check name property and if Name is in the Lower case then display Custom error.
 

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Demo.Models;
namespace Demo.Controllers
{
public class EmployeeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult Add()
{
return View();
}
[HttpPost]
public IActionResult Add(Employee employee)
{
if (ModelState.IsValid)
{
var upper = employee.Name.ToUpper();
var name = employee.Name;
if (name!=upper)
{
ModelState.AddModelError("Name", "Please Enter Name in Upper case");
}
              
}
return View();
}
}
}
       
1.7 Custom Model Validation

Conclusion


Validation Message tag helper and Validation summary Tag helper is used to display validation message if an error exists for the specified property in Model. Simply Validation Message and Validation summary are used to guide users for input.

Understanding Validation Tag Helpers in ASP.NET Core ASP.NET core provides a validation related tag use to display a validation message to the user. To display the validation message in view the validation tag generates the Html element. ASP.NET input tag is used to add client-side validation to input element based on data annotation defined in model. The Validation Tag helper is use to display validation message for invalid input to user. Validation Message Tag Helper (Used to displays a validation message for a single field of Model), and the Validation Summary Tag Helper (Used to displays a summary of all validation errors) are used in ASP.NET to display validation message. Validation Tag helpers in Asp.net core Asp.net core provides the following tag helper to display the validation message on the client-side: Validation Message Tag Helper Validation summary Tag Helper Validation Message Tag helper Validation Message Tag helper use element to display a validation error message for the model property specified in its attribute. Alternative for Validation Message in HTML Helper is Html.ValidationMessageFor Validation Summary Tag helper Validation Summary tag helper uses the element to display validation summary for property. Validation Summary tag helper uses an asp-validation-summary attribute to display a model validation summary on browser client. The alternative for Validation Summary in HTML Helper is @Html.ValidationSummary ValidationMessage : ValidationMessage is stringly typed (weakly type). A validation message is used to display a validation message if an error exists for the specified field in the Model. ValidationMessageFor : ValidationMessageFor is indeed strongly typed. Validation Message is used to display an error if data annotations attribute specified property in the model class. ValidationSummary : This ValidationSummary method is used to generates an unordered list (ul element) of validation messages that are in the ModelStateDictionary object.   Example of Validation Tag and Validation Summary: Step-1: Create an "Asp.net core web application" Open visual studio Create new Asp.net web application with model-View-controller template Visual studio opens your new project Step-2: Add Employee Model" Right-click on the Model folder and add Employee.cs Model using System; using System.ComponentModel.DataAnnotations; namespace Demo.Models { public class Employee { [Key] public int Id { get; set; } [Required(ErrorMessage = "Name is required")] public string Name { get; set; } [Required(ErrorMessage = "Date of birth is required")] [Display(Name = "Date of Birth")] [DataType(DataType.Date)] public DateTime DateofBirth { get; set; } [Required(ErrorMessage = "Address is required")] [StringLength(255)] public string Address { get; set; } [Required(ErrorMessage ="Mobile number is required")] [Display(Name = "Mobile Number")] [RegularExpression(@"^(?=.*[0-9])[- .()0-9]+$", ErrorMessage ="Invalid Mobile number")] public string Mobile { get; set; } } } Read More:Understanding Action Filters In Asp.Net Mvc Step-3: Add Employee Controller Right-click on the controller folder and add Employee controller Add Employee and add Method in Employee Controller   using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Demo.Models; namespace Demo.Controllers { public class EmployeeController : Controller { public IActionResult Index() { return View(); } public IActionResult Add() { return View(); } [HttpPost] public IActionResult Add(Employee employee) { if (ModelState.IsValid) { } return View(); } } } Use of ModelState.IsValid ModelState is used to check model validation is succeeded or not. If Model fields have definite types then it should be validated when returned to the controller. If any model field is not matched with their type then this ModelState.IsValid method returns false because these errors are defined in ModelState. Step-4: Add View for Add Method of Employee Controller. Add View for Add Method in Employee Controller. Right-click on the Add Action method and "Add" View and Write following code:   @model Demo.Models.Employee @{ ViewData["Title"] = "Add"; } Add Employee     Back to List @section Scripts { @{await Html.RenderPartialAsync("_ValidationScriptsPartial");} } Validation Message Tag helper is used on Html span tag with asp-validation-for attribute And Validation Message Tag helper generate following block of code   Validation Message Tag helper is used after input tag for the same field and used to display validation error message for that input. If Server-side validation error occur then span tag body is replaced with following code:   Mobile number is required Validation summary have following Value: ALL ALL option displays all the validation error for model and property.   Above Statement generate following HTML Code:   Above Statement generate following HTML Code:   If Server-side validation error occur then tag body is replaced with following code:   Model Model option display only model level validation. This option is used to display the validation error while asp-validation-for Tag helper is used in view page.   The model option does not generate any HTML script. None None option will not display any error message.   Step-5: Build and Run Build and run the application 1.6 Employee Add Page Wants to Talk with Our Highly Skilled .Net Core Developer ? Contact now. See here   How to Add Custom Error Message A validation summary tag helper is used to display a custom error message. ModelState.AddModelError() is used to display custom error. The ValidationSummary() method will display all the error messages added into the ModelState. Following block of code check name property and if Name is in the Lower case then display Custom error.     using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Demo.Models; namespace Demo.Controllers { public class EmployeeController : Controller { public IActionResult Index() { return View(); } public IActionResult Add() { return View(); } [HttpPost] public IActionResult Add(Employee employee) { if (ModelState.IsValid) { var upper = employee.Name.ToUpper(); var name = employee.Name; if (name!=upper) { ModelState.AddModelError("Name", "Please Enter Name in Upper case"); } } return View(); } } } 1.7 Custom Model Validation Conclusion Validation Message tag helper and Validation summary Tag helper is used to display validation message if an error exists for the specified property in Model. Simply Validation Message and Validation summary are used to guide users for input.
Kapil Panchal

Kapil Panchal

A passionate Technical writer and an SEO freak working as a Technical Content Manager at iFour Technolab, USA. With extensive experience in IT, Services, and Product sectors, I relish writing about technology and love sharing exceptional insights on various platforms. I believe in constant learning and am passionate about being better every day.

Build Your Agile Team

Enter your e-mail address Please enter valid e-mail
Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 

Blog Our insights

Quarkus vs Spring Boot - What’s Ideal for Modern App Development?
Quarkus vs Spring Boot - What’s Ideal for Modern App Development?

Spring Boot has long been a popular choice for developing custom Java applications. This is owing to its comprehensive features, impeccable security, and established ecosystem. Since...

Power BI Forecasting Challenges and Solutions
Power BI Forecasting Challenges and Solutions

Microsoft Power BI stands out for detailed data forecasting. By inspecting data patterns and using statistical models, Power BI provides a visual forecast of things to anticipate in...

Kotlin vs Java - Top 9 Differences CTOs Should Know
Kotlin vs Java - Top 9 Differences CTOs Should Know

Choosing the right programming language becomes crucial as it greatly influences the success of a software development project. When it comes to selecting the best programming language...