FluentValidation validator not being called
Asked Answered
S

2

6

I have a MVC 3 site but am using the non-MVC FluentValidation dll. I've created a validator class and in the constructor put all my RuleFors and then set an attribute on my model class thus

[FluentValidation.Attributes.Validator(typeof(MyValidator))]

The problem is that the constructor on the validator class never gets called. I think it might be because I am not using the MVC version of the dll, but then I could not get that version to work for me either.

Any help would be appreciated.

Thanks,

Sachin

Selfdevotion answered 11/6, 2012 at 16:42 Comment(0)
S
6

In your Application_Start make sure that you have initialized the custom fluent validation model validator provider otherwise nothing will happen:

FluentValidation.Mvc.FluentValidationModelValidatorProvider.Configure();

The FluentValidationModelValidatorProvider class is defined inside the FluentValidation.Mvc assembly. Please take a look at the documentation for integrating FluentValidation into an ASP.NET MVC site.

The validator will be triggered when you invoke a controller action taking a model decorated with the [Validator] attribute as argument:

[HttpPost]
public ActionResult Process(MyViewModel model)
{
    ...
}
Scipio answered 11/6, 2012 at 16:50 Comment(1)
Make sure to be using FluentValidation.Mvc, NOT FluentValidation.Mvc.WebApias the provider exists in both. Caught me out.Imperfection
B
2

Another reason your validation might not be called is if you have more than one constructor. I did this by accident and it was mystifying. I am so used to having a service constructor just pass in required services from dependency injection, that I did this by mistake:

public MyValidator(IJsonService jsonService)
{
    _jsonService = jsonService;
}

public MyValidator()
{
    RuleFor(x => x.ProductTechnologyId).GreaterThan(0).NotEmpty();
}

Only one constructor can be called! Oops!

Bluetongue answered 26/5, 2022 at 13:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.