<< Back to Blog

24 AUGUST 2017

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

ASP.NET Core allows you to use dependency injection in a custom model validation attribute.

Example: Email address unique attribute.

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

[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 existingInstances = dbContext.Users.Where(x => x.Email == email);

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

        return ValidationResult.Success;
    }

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