Really new to C #, ASP.NET MVC, and FluentValidation.
I have a user model, for example:
public class UserDetails{ public int ID { get; set; } public string UserName { get; set; } public string Email { get; set; } }
now I checked the username and email using FluentValidation, for example:
public AdminDetailsValidator(){ RuleFor(ad => ad.UserName).NotNull().Must(UniqueUserName(UserName)).WithMessage("UserName not Available"); RuleFor(ad => ad.Email).NotNull().Must(UniqueEmail(Email)).WithMessage("This Email id has already been registered"); ; } public bool UniqueUserName(string un) { if (UserDbContext.userDetails.SingleOrDefault(p => p.UserName == un) == null) { return true; } else { return false; } } public bool UniqueEmail(string em) { if (UserDbContext.userDetails.SingleOrDefault(p => p.Email == em) == null) { return true; } else { return false; } }
But I would prefer the more generic UniqueValidator, which I can use with several classes and properties. Or Atleast, I do not need to do a separate function for each property. So I looked at custom validators. But I have no idea how I can use this function for my needs. I want to do something like this:
RuleFor(ad => ad.Email).NotNull().SetValidator(new UniquePropertyValidator<UserDbContext>(userDetails.Email).WithMessage("This Email id has already been registered");
Is it possible to do this? I want to pass a DbContext as a parameter and a type property as an argument (or its variant, depending on what works). and the method can check the property against the table and return if it is unique or not.
source share