Serving Industries Worldwide

Innovative Ways - Satisfied Clientele

Understanding Validation Tag Helpers in ASP.NET Core


Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

 
 

Understanding-asp-dot-net

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"

  1. Open visual studio
  2. Create new Asp.net web application with model-View-controller template
  3. Visual studio opens your new project

create-web-app

1.1 Create a web application


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

  1. Right-click on the controller folder and add Employee controller
  2. 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.

  1. Add View for Add Method in Employee Controller.
  2. Right-click on the Add Action method and "Add" View and Write following code:

@model Demo.Models.Employee
@{
    ViewData["Title"] = "Add";
}<h2>Add</h2>
<h4>Employee</h4>
<hr /><div class="row"><div class="col-md-4"><form asp-action="Add"><div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
                
                <input asp-for="Name" class="form-control" /></div>
<div class="form-group">
                
                <input asp-for="DateofBirth" class="form-control" /></div>
<div class="form-group">
                
                <input asp-for="Address" class="form-control" /></div>
<div class="form-group">
                
                <input asp-for="Mobile" class="form-control" /></div>
<div class="form-group">
                <input class="btn btn-default" type="submit" value="Create" /></div></form></div></div>
<div>
    <a asp-action="Index">Back to List</a></div>

@section Scripts {
    @{await Html.RenderPartialAsync(&amp;quot;_ValidationScriptsPartial&amp;quot;);}
}

 

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
 


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


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>

Validation summary have following Value:

ALL

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

<div asp-validation-summary="All" class="text-danger"></div>

Above Statement generate following HTML Code:
 

<div class="validation-summary-valid" data-valmsg-summary="true"><ul><li style="display:none"></li></ul></div>

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

<div class="validation-summary-valid" data-valmsg-summary="true"><ul><li></li><li style="display:none">Name is required</li><li></li><li style="display:none">Date of birth is required</li><li></li><li style="display:none">Address  is required</li><li></li><li style="display:none">Mobile number is required</li><li></li></ul></div>


 

opt-example

1.2 ALL option 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.
 

<div asp-validation-summary="Model" class="text-danger"></div>

The model option does not generate any HTML script.

dmodel-example

1.3 Model Only option

None

None option will not display any error message.
 

<div asp-validation-summary="None" class="text-danger"></div>


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

custom-validation

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-asp-dot-net

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"

  1. Open visual studio
  2. Create new Asp.net web application with model-View-controller template
  3. Visual studio opens your new project

create-web-app

1.1 Create a web application


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

  1. Right-click on the controller folder and add Employee controller
  2. 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.

  1. Add View for Add Method in Employee Controller.
  2. Right-click on the Add Action method and "Add" View and Write following code:

@model Demo.Models.Employee
@{
    ViewData[&amp;quot;Title&amp;quot;] = &amp;quot;Add&amp;quot;;
}<h2>Add</h2>
<h4>Employee</h4>
<hr /><div class="row"><div class="col-md-4"><form asp-action="Add"><div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
                
                <input asp-for="Name" class="form-control" /></div>
<div class="form-group">
                
                <input asp-for="DateofBirth" class="form-control" /></div>
<div class="form-group">
                
                <input asp-for="Address" class="form-control" /></div>
<div class="form-group">
                
                <input asp-for="Mobile" class="form-control" /></div>
<div class="form-group">
                <input class="btn btn-default" type="submit" value="Create" /></div></form></div></div>
<div>
    <a asp-action="Index">Back to List</a></div>

@section Scripts {
    @{await Html.RenderPartialAsync(&amp;quot;_ValidationScriptsPartial&amp;quot;);}
}

 

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
 


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


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>

Validation summary have following Value:

ALL

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

<div asp-validation-summary="All" class="text-danger"></div>

Above Statement generate following HTML Code:
 

<div class="validation-summary-valid" data-valmsg-summary="true"><ul><li style="display:none"></li></ul></div>

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

<div class="validation-summary-valid" data-valmsg-summary="true"><ul><li></li><li style="display:none">Name is required</li><li></li><li style="display:none">Date of birth is required</li><li></li><li style="display:none">Address  is required</li><li></li><li style="display:none">Mobile number is required</li><li></li></ul></div>


 

opt-example

1.2 ALL option 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.
 

<div asp-validation-summary="Model" class="text-danger"></div>

The model option does not generate any HTML script.

dmodel-example

1.3 Model Only option

None

None option will not display any error message.
 

<div asp-validation-summary="None" class="text-danger"></div>


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

custom-validation

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.