If we have a validation requirement that cannot be implemented using the built-in attributes, we can create a custom validation attribute.
- Create a class that derives from the built-in abstract
ValidationAttribute
class and overrideIsValid()
method. IsValid()
method returnsnull
if there are no validation errors, otherwise aValidationResult
object.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/