Zorev Gnoz
Zorev Gnoz

Reputation: 251

FluentValidation Check Duplicate Values with DB

I am trying to make sure that the user input cannot be the same name as the ones I have in the database.

How do I do that using Fluent Validation?

I have tried this but it came up with some errors.

This is my current code:

RuleFor
(x => x.Name)
.NotEmpty().WithMessage("The name cannot be empty!");

Example for the (User) DB will be:

Name, Age

The name should not be duplicated.

Upvotes: 1

Views: 2873

Answers (1)

Marlonchosky
Marlonchosky

Reputation: 526

In the link referred to, they give a suitable solution. However, I suggest you use design patterns (like the repository pattern), and principles (like dependency injection). One way to do the validation you need (no names duplicates) is:

  1. Define a repository interface and a method to get your data from the database:

    public interface IMyClassToValidateRepository {
        Task<IList<MyClassToValidate>> GetDataAsync();
    }
    
  2. In your validator class, pass an object of the repository in its constructor (this object will be resolve by dependency injection). Then define your validation like this (look that I'm using async methods. In case you don't need asynchronous methods, you will need to converting to its synchronous version):

    public class MyClassToValidateValidator : AbstractValidator<MyClassToValidate> {
        public MyClassToValidateValidator(IMyClassToValidateRepository repository) {
            RuleFor(x => x.Name)
                .MustAsync(async (name, ct) => 
                    (await repository.GetDataAsync()).All(x => x.Name != name));
        }
    }
    

The class that I used like example:

public class MyClassToValidate {
    public string Name { get; set; }
}

Upvotes: 1

Related Questions