DEV Community

Cover image for Understanding Validation Tag Helpers in ASP.NET Core
Harshal Suthar
Harshal Suthar

Posted on • Originally published at ifourtechnolab.com

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

Image description

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; }

}
}

Enter fullscreen mode Exit fullscreen mode

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();
}
}
}

Enter fullscreen mode Exit fullscreen mode

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";
}

Enter fullscreen mode Exit fullscreen mode

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:

<span class="field-validation-valid text-danger " data-valmsg-for=" Mobile " data-valmsg-replace="true"> Mobile number is required </span>

Enter fullscreen mode Exit fullscreen mode

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:

Image description

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.

Image description

None
None option will not display any error message.

Step-5: Build and Run

Build and run the application

Image description

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();
}
}
}

Enter fullscreen mode Exit fullscreen mode

Image description

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.

Top comments (0)