Note that there are some explanatory texts on larger screens.

plurals
  1. POFluent Validation in ASP.net MVC - Database Validations
    primarykey
    data
    text
    <p>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. </p> <ol> <li>Should Fluent Validation be used in this case?</li> <li>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.</li> </ol> <p>An example of what I'm trying to validate might:</p> <p>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.</p> <p><strong>Edit</strong><br> Here is a code example of a regular validation in Fluent Validation framework:</p> <pre><code>[Validator(typeof(CreateProductViewModelValidator))] public class CreateProductViewModel { public string Name { get; set; } public decimal Price { get; set; } } public class CreateProductViewModelValidator : AbstractValidator&lt;CreateProductViewModel&gt; { public CreateProductViewModelValidator() { RuleFor(m =&gt; m.Name).NotEmpty(); } } </code></pre> <p>Controller:</p> <pre><code>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"); } </code></pre> <p>As you can see, I never create the Validator myself. This works because of the following line in <code>Global.asax</code>:</p> <pre><code>FluentValidation.Mvc.FluentValidationModelValidatorProvider.Configure(); </code></pre> <p>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.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload