Fluent Validation in ASP.net MVC - Database Validations

Dismissile picture Dismissile · Nov 29, 2011 · Viewed 6.9k times · Source

I'm using the Fluent Validation framework in my ASP.net MVC 3 project. So far all of my validations have been very simple (make sure string is not empty, only a certain length, etc.) but now I need to verify that something exists in the database or not.

  1. Should Fluent Validation be used in this case?
  2. If the database validation should be done using Fluent Validation, then how do I handle dependencies? The validator classes are created automatically, and I would need to somehow pass it one of my repository instances in order to query my database.

An example of what I'm trying to validate might:

I have a dropdown list on my page with a list of selected items. I want to validate that the item they selected actually exists in the database before trying to save a new record.

Edit
Here is a code example of a regular validation in Fluent Validation framework:

[Validator(typeof(CreateProductViewModelValidator))]
public class CreateProductViewModel
{
    public string Name { get; set; }
    public decimal Price { get; set; }
}

public class CreateProductViewModelValidator : AbstractValidator<CreateProductViewModel>
{
    public CreateProductViewModelValidator()
    {
        RuleFor(m => m.Name).NotEmpty();
    }
}

Controller:

public ActionResult Create(CreateProductViewModel model)
{
    if(!ModelState.IsValid)
    {
        return View(model);
    }

    var product = new Product { Name = model.Name, Price = model.Price };
    repository.AddProduct(product);

    return RedirectToAction("Index");
}

As you can see, I never create the Validator myself. This works because of the following line in Global.asax:

FluentValidation.Mvc.FluentValidationModelValidatorProvider.Configure();

The problem is that now I have a validator that needs to interact with my database using a repository, but since I'm not creating the validators I don't know how I would get that dependency passed in, other than hardcoding the concrete type.

Answer

mreyeros picture mreyeros · Dec 8, 2011

This link may help you implement what you are looking for without having to manually instantiate and manually validate you models. This link is directly from the FluentValidation discussion forum.