Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to integrate FluentValidation into MVC4

I have made a simple model that has FluentValidation in it but it does not seem to work.

  • My database is updating with empty name and passing TryUpdateModel()
  • I don't get client-side validation errors when I submit my form

I have tried to add FluentValidationModelValidatorProvider.Configure(); in Application_Start() but it shows that it cannot find FluentValidationModelValidatorProvider even though I added using class. I also tried to add [Validator(typeof(Category))] on top of my model class but didn't do anything. This us the resource I've been looking for information.

Model

public class Category
{
    public int ID { get; set; }
    public string Name { get; set; }
    virtual public ICollection<Image> Images { get; set; }
}

public class CategoryValidator : AbstractValidator<Category>
{
    public CategoryValidator()
    {
        RuleFor(x => x.Name).NotEmpty().WithMessage("Category name is required.");
    }
}

Controller

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Category c)
{
    var category = _db.Categories.Where(x => x.ID == c.ID).SingleOrDefault();
    if (category == null) return HttpNotFound();

    // Update model and return to category list
    if (TryUpdateModel(category)) // it passes with empty name and saves changes
    {
        _db.SaveChanges();
        return RedirectToAction("index", "category");
    }

    // Something is wrong, return view back
    return View(c);
}
like image 496
Stan Avatar asked Nov 15 '12 19:11

Stan


1 Answers

It sounds like you're missing the FluentValidation.Mvc reference. Try installing the FluentValidation.MVC4 NuGet package.

Then follow the MVC instructions.

like image 156
jrummell Avatar answered Nov 18 '22 20:11

jrummell