Reputation: 46750
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
Upvotes: 6
Views: 5975
Reputation: 25079
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!
Upvotes: 2
Reputation: 1038830
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)
{
...
}
Upvotes: 6