I’m a newbie in asp.net. I want to create my custom validation attribute to check, if a user with the same email exists. So, I need to assign an IUserService through the constructor and dependency injection. After that, I want to use the IUserService method in the validation method to check if the user already exists.
This is the code for my custom attribute.
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class EmailIsAlreadyExist : ValidationAttribute
{
public new string ErrorMessage { get; set; }
readonly IUserService _userService;
public EmailIsAlreadyExist(IUserService userService)
{
_userService = userService;
}
public override bool IsValid(object value)
{
string email = (string)value;
if (_userService.CheckIfUserWithTheEmailIsAlreadyExist(email))
{
return false;
}
return true;
}
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentCulture,
UserStringConstants.UserIsAlreadyExistErrorMessage, name);
}
}
And I try to use my custom attribute here.
namespace WebApiForHikka.WebApi.Dto.Users;
public class UserRegistrationDto
{
[EmailAddress(ErrorMessage = SharedStringConstants.EmailIsntFormatedCorrectlyErrorMessage)]
[EmailIsAlreadyExist()]
[Required]
public required string Email { get; set; }
[Required]
[RegularExpression(UserStringConstants.SimplePasswordRegExpression, ErrorMessage = UserStringConstants.SimplePasswordErrorMessage)]
public required string Password { get; set; }
[Required]
public required string Role { get; set; }
}
But I get an error which tells me that I don’t have a constructor with zero params.
By the way, all my dtos are in a liberary, because of it, I inject my dependency in a project for webApi controller.
So, is it possible to use dependency injection with a custom validation attribute?
Black foxi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.