Custom Attribute Validation in ASP.NET Core

This blog is going to explain what is the Custom Attribute Validation in ASP.NET Core. When the built-in verification attributes are not sufficient to handle validation conditions, you can create your own custom validation attributes. Let’s see how to achieve this step by step.

Step 1:
The following is the WeeklyEmailAttribute.cs class. Here I have implemented the ValidationAttribute class and override the IsValid method. The IsValid method verifies that the IsAgreed property is true and that the email address is empty. If the condition is true, it will issue a validation message. Otherwise, it will return a success verification result.

WeeklyEmailAttribute.cs
using System.ComponentModel.DataAnnotations;

namespace SampleWebApplication.Validation
{
    public class WeeklyEmailAttribute : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value,
            ValidationContext validationContext)
        {
            var sample = (SampleModel)validationContext.ObjectInstance;

            if (sample.IsAgreed && string.IsNullOrWhiteSpace(sample.EmailAddress))
            {
                return new ValidationResult("Enter Email ID to Receive Weekly Emails.");
            }

            return ValidationResult.Success;
        }
    }
}

Step 2:
The next step is a SampleModel class. Here I have decorated the FirstName and LastName properties with [Required] attributes, i.e. they are mandatory. And I have decorated the EmailAddress property with the [WeeklyEmail] attribute.

SampleModel.cs
public class SampleModel
{
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
    public bool IsAgreed { get; set; }
    [WeeklyEmail]
    public string EmailAddress { get; set; }
}

Step 3:
The third step is View creation. This view will receive the First Name, Last Name, Is Agress and Email Address. To display the validation error message, I have added the span element with asp-validation-for attribute. Finally, I added the submit button to submit the page to the server.

Index.cshtml
@{
    ViewData["Title"] = "Custom Attributes Model Validation";
}
@model SampleModel

@{
<form asp-controller="Home" asp-action="Index" method="post">
    <table>
        <tr>
            <td>
                First Name: <input type="text" asp-for="FirstName" />
                <span asp-validation-for="FirstName" class="text-danger"></span>
            </td>
        </tr>
        <tr>
            <td>
                Last Name: <input type="text" asp-for="LastName" />
                <span asp-validation-for="LastName" class="text-danger"></span>
            </td>
        </tr>
        <tr>
            <td>
                <input type="checkbox" asp-for="IsAgreed" />
                If you agree to receive the weekly email, check the checkbox
            </td>
        </tr>
        <tr>
            <td>
                Email Address: <input type="text" asp-for="EmailAddress" />
                <span asp-validation-for="EmailAddress" class="text-danger"></span>
            </td>
        </tr>
    </table>
    <input type="submit" value="Submit" />
</form>
}

Step 4:
The final one is a Controller code. The controller has 2 Index methods. One is Get and another one is Post method. The Get method sends an empty sample model to the View. The Post Index method receives the SampleModel from view and checks whether the SampleModel is valid or not. If it is valid it will return the message page. Otherwise, it will return to the same page with the error validation message.

HomeController.cs
public IActionResult Index()
{
    SampleModel sampleModel = new SampleModel();
    return View(sampleModel );
}

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Index(SampleModel sampleModel)
{            
    if (ModelState.IsValid)
    {
        return View("Message");
    }
    return View(sampleModel);
}

Output
The following image illustrates how custom validation works. When users check the ‘If you agree to receive the weekly email, check the checkbox’, checkbox and click the submit button, it will display a validation message for entering the email address. When the user uncheck the checkbox, the page does not check the empty email address textbox.

I hope this helps you. Keep coding.

Comments

Popular posts from this blog

Entity Framework Core (EF) with SQL Server LocalDB

Creating a C# Azure Function with Visual Studio: Step-by-Step Guide

Exploring EventCallback in Blazor: Building Interactive Components