Article

Add validation to an ASP.NET Core MVC app

In this article we will learn Add validation to an ASP.NET Core MVC app.

We want to make all field of Model Employee Class Name,Office Email and Title fields required. If the required values are not provided and the form is submitted we want to display required validation errors as shown below.

add-validation-asp-net-core-mvc-app

If you enter invalid email, This errors as shown below

add-validation-asp-net-core-mvc-app
Valiidation In Asp.Net Core MVC

Learn step by step Add validation to an ASP.NET Core MVC app.
Validation logic is added to the Employee model. You ensure that the validation rules are enforced any time a user creates a Employee.

Add validation rules to the Employee model

To make Name, Email,Title field a required field, apply Required attribute on the property of the Employee model class. Required attribute is in System.ComponentModel.DataAnnotations namespace.

Add this namespace for Add validation to an ASP.NET Core MVC app

System.ComponentModel.DataAnnotations

Empoyee.cs :Update the Employee class to take advantage of the built-in Required, StringLength, RegularExpression, and Range validation attributes.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace EmplloyeeManagement.Models
{
    public class Employee
    {
        public int Id { get; set; }
        [Required(ErrorMessage ="Please provide a value for name Field")]
        public string Name { get; set; }
        [Display(Name="Office Email")]
        [RegularExpression(@"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$",
        ErrorMessage = "Invalid email format")]
        [Required]
        public string Email { get; set; }
        [StringLength(60, MinimumLength = 3)]
        [Required]
        public string Title { get; set; }

    }
}

Key Point:
1. The RegularExpression attribute is used to limit what characters can be input.

How validation works to an ASP.NET Core MVC app

The following code shows the two Create methods.

 [HttpGet]
        public ViewResult Create()
        {
            return View();
        }
        [HttpPost]
        public IActionResult Create(Employee employee)
        {
            if (ModelState.IsValid) { 
            Employee newEmployee = _employeeRepository.Add(employee);
            return RedirectToAction("Details", new { id = newEmployee.Id });
             }
            return View();
        }

The first (HTTP GET) Create action method displays the initial Create form. The second ([HttpPost]) version handles if the form post. The second Create method (The [HttpPost] version) calls ModelState.IsValid to check whether the employee has any validation errors. Calling this method evaluates any validation attributes that have been applied to the object. If validation has failed we return the same view so the user can provide the required data and resubmit the form.

Create.cshtml view template is shown in the following markup:

@model Employee

@{ 
    ViewBag.Title = "Create Employee";
   Layout = "~/Views/Shared/_Layout.cshtml";
}

<form asp-controller="home" asp-action="Create" method="post" class="mt-3">
    <div class="form-group row">
        <label asp-for="Name" class="col-sm-2 col-form-label"></label>
        <div class="col-sm-10">
            <input asp-for="Name" class="form-control" placeholder="Name" />
            <span asp-validation-for="Name" class="text-danger"></span>
        </div>
    </div>
    <div class="form-group row">
        <label asp-for="Email" class="col-sm-2 col-form-label"></label>
        <div class="col-sm-10">
            <input asp-for="Email" class="form-control" placeholder="Email" />
            <span asp-validation-for="Email" class="text-danger"></span>
        </div>
    </div>
    <div class="form-group row">
        <label asp-for="Title" class="col-sm-2 col-form-label"></label>
        <div class="col-sm-10">
            <input asp-for="Title" class="form-control" placeholder="Title" />
            <span asp-validation-for="Title" class="text-danger"></span>
        </div>
    </div>
    <div asp-validation-summary="All" class="text-danger"></div>
    <div class="form-group row">
        <div class="col-sm-10">
            <button type="submit" class="btn btn-primary">Create</button>
        </div>
    </div>
</form>

To display validation errors use asp-validation-for and asp-validation-summary tag helpers. This asp-validation-for tag helper displays a validation message for a single property of our Eployee model class. asp-validation-summary tag helper displays a summary of validation errors.

To display the validation error associated with the Name, Email, Title property of the Employee class use asp-validation-for tag helper on a element as shown above.

Leave a Reply

Your email address will not be published. Required fields are marked *