ASP.NET Core Blazor | How to create custom validation attribute


asp-net-create-custom-validation-attribute

In this video we will discuss how to create and use a custom validation attribute in Blazor.

Blazor built-in validation attributes

For most use cases Blazor has several built-in attributes for model validation. We discussed some of these attributes in Part 22 of this Blazor tutorial. Some of the built-in attributes are listed below.

  • Required
  • Range
  • StringLength
  • Compare
  • Regular Expression
  • MinLength
  • MaxLength

Custom Validation Attribute in Blazor

If you have a complex validation requirement that you cannot implement using the built-in attributes, you can create a custom validation attribute and reuse it in your project or even in multiple projects if you create it in a separate class library project.

Custom Validation Attribute Example

Our business requirement is to only allow email address where the domain name is pragimtech.com. If any other domain name is used, we want to display a validation error. Let's create a custom validator to implement this.

asp-net core blazor create custom validation attribute

Create custom validation attribute

To create a custom validation attribute, create a class that derives from the built-in abstract ValidationAttribute class and override IsValid() method.

AllowedEmailDomainAttribute.cs

public class AllowedEmailDomainAttribute : ValidationAttribute
{
    public AllowedEmailDomainAttribute(string allowedDomain)
    {
        AllowedDomain = allowedDomain;
    }

    public string AllowedDomain { get; }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value == null || value.ToString().Length == 0)
        {
            return new ValidationResult("Email address is required");
        }
        else
        {
            if (value.ToString().IndexOf('@') == -1)
            {
                return new ValidationResult($"Invalid email address");
            }

            string[] strings = value.ToString().Split('@');

            if (strings[1].ToUpper() == AllowedDomain.ToUpper())
            {
                return ValidationResult.Success;
            }
            else
            {
                return new ValidationResult(this.ErrorMessage ?? $"Email domain must be {AllowedDomain}");
            }
        }
    }
}

How to use custom validation attribute in Blazor

public class Employee
{
    [AllowedEmailDomain("pragimtech.com")]
    public string Email { get; set; }
    // rest of the properties
}
  • Use the custom validation attribute just like any other built-in validation attribute.
  • When using an attribute, the Attribute part of the name is optional. You can use the fullname (AllowedEmailDomainAttribute) or just AllowedEmailDomain.
  • Email property is decorated with AllowedEmailDomain attribute which is our custom validation attribute.

Override custom validation attribute error message

public class Employee
{
    [AllowedEmailDomain("pragimtech.com", ErrorMessage = "Invalid domain name")]
    public string Email { get; set; }
    // rest of the properties
}
  • Explicitly set ErrorMessage property to override the error message already specified in the AllowedEmailDomainAttribute class.
  • The ErrorMessage property is inherited from the built-in base class ValidationAttribute.




© 2020 Pragimtech. All Rights Reserved.