I use the Fluent Validation framework in my ASP.net MVC 3 project. So far, all my checks have been very simple (make sure the string is not empty, only a certain length, etc.), but now I need to check that something it exists in the database or not.
- Should Fluent Validation be used in this case?
- If database validation should be done using Fluent Validation, then how do I handle dependencies? Validator classes are created automatically, and I need to somehow pass it to one of my repository instances to query my database.
An example of what I'm trying to verify might be:
I have a drop-down list on my page with a list of selected items. I want to confirm that the item they selected actually exists in the database before trying to save a new record.
Edit
Here is an example of a regular check code in Fluent Validation Fluct:
[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 a 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 the repository, but since I do not create validators, I do not know how to get this dependent information, except for hard encoding. concrete type.
source share