<< Back to Blog

24 AUGUST 2017

.NET Core: How to create a Custom Validation Attribute (e.g. [UniqueEmail]) with Dependency Injection

It is possible to create a custom validation attribute for a Model with dependency injection in ASP.NET Core.

An example of why you may want to do this is to check if an email address is already taken in the database during user Registration.

The constructor of the custom attribute class does not allow you to inject a service/helper, but instead you can do it in the IsValid() method like this:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class UniqueEmailAttribute : ValidationAttribute
{
    private ApplicationDbContext _dbContext
    private const string DefaultErrorMessage = "This email is already taken."

    public UniqueEmailAttribute() : base(DefaultErrorMessage){}

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        _dbContext = (ApplicationDbContext)validationContext.GetService(typeof(ApplicationDbContext))

        if (value != null)
        {
            string email = (string)value
            var existingUsernameInstances = _dbContext.Users.Where(x => x.Email == email)

            if (existingUsernameInstances.Any())
            {
                return new ValidationResult(FormatErrorMessage(validationContext.DisplayName))
            }
        }

        return ValidationResult.Success
    }

    public override string FormatErrorMessage(string name)
    {
        return string.Format(ErrorMessageString, name)
    }
}