Home > OS >  ASP.NET Core Web API - Custom Unique Email Validation using Data Annotation not working
ASP.NET Core Web API - Custom Unique Email Validation using Data Annotation not working

Time:09-08

I have Custom Unique Email validation using ASP.NET Core-6 Web API Entity Framework project

public class UserUniqueEmailValidator : ValidationAttribute
{
    private readonly ApplicationDbContext _dbContext;
    public UserUniqueEmailValidator(ApplicationDbContext dbContext)
    {
        _dbContext = dbContext;
    }
    public bool IsUniqueUserEmailValidator(string email)
    {
        if (_dbContext.ApplicationUsers.SingleOrDefault(x => x.Email.ToLower() == email.ToLower()) == null) return true;
        return false;
    }
}

Then I called it here:

    [Required(ErrorMessage = "Email field is required. ERROR!")]
    [StringLength(100, ErrorMessage = "Email field must not exceed 100 characters.")]
    [EmailAddress(ErrorMessage = "The Email field is not a valid e-mail address.")]
    [UserUniqueEmailValidator(ErrorMessage = "Email already exists !!!")]
    public string Email { get; set; }

But I got this error:

There is no argument given that corresponds to the required formal parameter 'dbContext' of 'UserUniqueEmailValidator.UserUniqueEmailValidator(ApplicationDbContext)'

How do I resolve it?

Thanks

CodePudding user response:

Instead of implementing your own validation attribute, use the Remote Validation attribute.

Here is an example implementation

[Remote("ValidateEmailAddress","Home")]
public string Email { get; set; }

The validateEmailAddress implementation

public IActionResult ValidateEmailAddress(string email)
{
    return Json(_dbContext.ApplicationUsers.Any(x => x.Email != email) ?
            "true" : string.Format("an account for address {0} already exists.", email));
}

Hope it helps.

CodePudding user response:

Just as the error indicates: Validator's constructor contains the ApplicationDbContext parameter which is not valid;

Also, IsUniqueUserEmailValidatormethod has not been called ,so the codes inside it will never be executed

If you want to custom ValidationAttribute you could overrride protected virtual ValidationResult? IsValid(object? value, ValidationContext validationContext)

and access ApplicationDbContext as below:

protected override ValidationResult? IsValid(
        object? value, ValidationContext validationContext)
        {
            var context = validationContext.GetService<ApplicationDbContext>();
            //add your logical codes here



           return ValidationResult.Success;
        }

For more details,you could check this document

  • Related