简体   繁体   中英

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

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

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.

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

Also, IsUniqueUserEmailValidator method 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) 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM