FluentValidation AddToModelState

HOORAY FOR THIS!

I was working on some admin functionality, and I added a validator to a model. The problem is the forms are contained within Telerik MVC Extensions tabs, so the validators for one tab are applied even if you are on a different tab. No dice! I really wanted to offer some nice error messages though, so I refused to quit! 🙂

I thought, “why can’t I just new up my validator manually”. I did this, and at first I wasn’t seeing what I needed. I eventually found that I had to get the result of validator.Validate(model) and then check result.IsValid. I was originally assuming I’d just be checking validator.IsValid. Anyway, here is what I had to that point:

var validator = 
    new Nop.Admin.Validators.Catalog
        .AddProductRelationshipAttributeValidator(_localizationService);
var result = validator.Validate(model);
if (result.IsValid == false) {
    // Do some error stuff here
}

The only thing now was how to get the result errors into the model state? I found a great thread on the FluentValidation discussion board that was asking the same thing – do I have to iterate the errors and manually add them to the ModelState? It turns out the answer is “yes”, but there is the handy extension method mentioned in the subject! TADA! So now, I have this nice bit of code:

var validator = 
    new Nop.Admin.Validators.Catalog
        .AddProductRelationshipAttributeValidator(_localizationService);
var result = validator.Validate(model);
if (result.IsValid == false) {
    Response.StatusCode = 400;
    result.AddToModelState(ModelState, "");
    return ModelState.JsonValidation(JsonRequestBehavior.AllowGet);
}

The ModelState.JsonValidation bit is another extension method I have to put the ModelState into a standardized JSON result that I then pass through a couple of js functions. Those functions make sure the validation passes, and if the validation does not pass it puts the errors in the validation summary manually. It is all pretty handy stuff.

If anyone has any better ideas, I am all ears!