Blazor Custom Form Validation

If we have a validation requirement that cannot be implemented using the built-in attributes, we can create a custom validation attribute.

  1. Create a class that derives from the built-in abstract ValidationAttribute class and override IsValid() method.
  2. IsValid() method returns null if there are no validation errors, otherwise a ValidationResult object.
  3. ValidationResult accepts 2 parameters – Validation error message and the property name with which this validation error message must be associated with.
using System.ComponentModel.DataAnnotations;

namespace EmployeeManagement.Models.CustomValidators
{
    public class EmailDomainValidator : ValidationAttribute
    {
        public string AllowedDomain { get; set; }

        protected override ValidationResult IsValid(object value, 
            ValidationContext validationContext)
        {
            string[] strings = value.ToString().Split('@');
            if (strings[1].ToUpper() == AllowedDomain.ToUpper())
            {
                return null;
            }

            return new ValidationResult($"Domain must be {AllowedDomain}",
            new[] { validationContext.MemberName });
        }
    }
}
public class Employee
{
    [EmailDomainValidator(AllowedDomain = "pragimtech.com")]
    public string Email { get; set; }
}

References
https://www.pragimtech.com/blog/blazor/blazor-custom-form-validation/