0

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

1
  • Seems like EF and dbContext is not properly defined at project startup. Commented Sep 7, 2022 at 10:19

2 Answers 2

0

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.