Question

I am using FluentValidation and a Service Layer for my MVC application.

I have a question regarding where you would put logic to check for duplicate items.

Say you have a CategoryService and a CategoryValidator, would you put the logic to check for a duplicate category name in the service or in the validator using the Must predicate?

In either method below, I do common things like checking for a valid category name in the validator.

Method 1

public bool AddCategory(Category category)
{
    var validationResult = validationService.Validate(category);

    if (!validationResult.IsValid)
        return false;

    categoryRepository.Add(category);

    return true;
}

public CategoryValidator(ICategoryService service)
{
    RuleFor(x => x.Name)
        .NotEmpty()
        .Must((category, name) =>
        {
            return service.GetCategories().SingleOrDefault(x => x.Name == name) == null;
        });
}

Method 2

public bool AddCategory(Category category)
    {
        var existing = categoryRepository.Query().SingleOrDefault(x => x.Name == category.Name);

        if (existing != null)
            return false;

        categoryRepository.Add(category);

        return true;
    }
Was it helpful?

Solution

There is no point in doing the validation in both places. It should be sufficient to do all validation in the validator.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top