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);
}
It sounds like you’re missing the
FluentValidation.Mvcreference. Try installing the FluentValidation.MVC4 NuGet package.Then follow the MVC instructions.