Hatjhie
Hatjhie

Reputation: 1365

How to intercept my model before FluentValidation validate in ASP.NET MVC?

Assumptions:

  1. FluentValidation is integrated with my ASP.NET MVC 5 web server by using Dependency Injection.
  2. FluentValidation rule has been setup to validation my model property, let's say propA.

Let's say I have a page that post to ASP.NET MVC 5 web server, and my model propA is set according to the TextBox value input by user. But I am wondering, if I could possibly inject my own serialization method to change the value of propA before the FluentValidation runs in the web server validating my model?

Is it possible?

Upvotes: 2

Views: 1295

Answers (1)

Electrionics
Electrionics

Reputation: 6772

Validation for both FluentValidation and DataAnnotation approaches work after model was binded, so you can create custom ModelBinder for your model:

public class YourBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var model = (YourModel)base.BindModel(controllerContext, bindingContext);

        model.PropA = model.PropA + " catched before validation";
        return model;
    }
}

Register it in global.asax

protected void Application_Start()
{
    ModelBinders.Binders.Add(typeof(YourModel), new YourBinder()); // asssociate model type with binder
}

And pass parameter of your model type in action:

public ActionResult Submit(YourModel model) //YourBinder automatically used
{
    if (ModelState.IsValid)
    {
        //...
    }
}

Upvotes: 1

Related Questions