×

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.

 

Table of Content

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.   Table of Content 1. Validation Tag helpers in Asp.net core 2. Validation Message Tag helper 3. Validation Summary Tag helper 3.1. Step-1: Create an "Asp.net core web application" 3.2. Step-2: Add Employee Model 3.3. Step-3: Add Employee Controller 3.4. Step-4: Add View for Add Method of Employee Controller. 3.5. Step-5: Build and Run 4. Conclusion 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.

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

Next-Gen Programming Languages: Shaping the Future of Software Development in 2024
Next-Gen Programming Languages: Shaping the Future of Software Development in 2024

Introduction Imagine standing in line at the grocery store, waiting to pay for groceries. You pull out your phone and scan each item’s barcode with a single tap. This seemingly...

20 Essential DevOps Tools That Businesses Should Embrace In 2024
20 Essential DevOps Tools That Businesses Should Embrace In 2024

Before navigating into the world of DevOps, it's important to know what DevOps is exactly. DevOps is a methodology that uses continuous integration, continuous delivery, and automation to shorten the software delivery lifecycle (SDLC). More than just a set of practices, DevOps embodies a culture and a philosophy that bridges the gap between developers (Dev) and IT operations (Ops) teams.

Microsoft PowerApps Development: Is It A Low-Code Or No-Code Approach
Microsoft PowerApps Development: Is It A Low-Code Or No-Code Approach

Microsoft PowerApps has become the preferred digital solution, particularly for non-tech clients. It is a simple and easy-to-use app development platform that does not require much coding and can help you create personalized apps effortlessly with drag-and-drop capabilities.