Article

Validate Email In Asp.Net Core MVC

In this article we will learn, Validate Email In Asp.Net Core MVC.

We want to make Office Email fields required of Employee model class. If the required values are not provided and the form is submitted we want to display required validation errors as shown below.

validate-email-asp-net-core-mvc

If you enter invalid email formate, This errors as shown below

validate-email-asp-net-core-mvc

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 Email 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 Validate Email In Asp.Net Core MVC.

System.ComponentModel.DataAnnotations

Empoyee.cs :Update the Employee class to take advantage of the built-in Required, RegularExpression 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; }
        [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; }
    }
}

Key Point:
1. The RegularExpression attribute is used to limit what characters can be input. This expression that checks for valid email addresses.
2. Display Attribute : This is not a validation attribute. It is generally used for display purpose in the UI.

How validation works

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:

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 Office Email property of the Employee class use asp-validation-for tag helper on a element as shown below.

@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="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 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>

Leave a Reply

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