Monday, December 23, 2013

MVVM light and Model Validation

I have been using the MVVM light toolkit for a project recently. It is a great toolkit but is missing a couple things and Laurent Bugnion does a good job trying to cover those holes. One of the things the toolkit does not support is Validation. The good news is there is a great CodePlex project out there call Fluent Validation that makes this pretty easy to add and really powerful. My objective was to add validation to my model so I could call “IsValid” on the model itself (similar to the MVC attribute approach). Fluent Validation has you create a new class file that holds you validation rules for a given model. This is the approach I took to enable each model to have an “IsValid” property and a “Errors” property that returns the validation errors.

First I setup my ValidationFactory:

public class ValidatorFactory : FluentValidation.ValidatorFactoryBase
    public override FluentValidation.IValidator CreateInstance(Type validatorType)
        return SimpleIoc.Default.GetInstance(validatorType) as FluentValidation.IValidator;

Next I used the SimpleIoC object that comes with MVVM light to register my validator class in the ViewModelLocator :

// Register Validator
SimpleIoc.Default.Register<IValidator<Car>, CarValidator>();

You can set up your CarValidator pretty easy and follow the examples on the Fluent Validation site so I will not go through all that. The next part was figuring out how to have all my models have the functionality I needed without adding custom code to all my models. I wanted a basemodel class to handle this for all models that are built on top of it. Here is what I came up with.

Create a BaseModel class that all Models will inherit from.

   1: public abstract class ModelBase
   2: {
   3:     private IValidator _validator;
   4:     private IValidator Validator
   5:     {
   6:         get
   7:         {
   8:             if (_validator == null)
   9:             {
  10:                 var valFactory = new ValidatorFactory();
  11:                 _validator = valFactory.GetValidator(this.GetType().UnderlyingSystemType);
  12:             }
  13:             return _validator;
  14:         }
  15:     }
  17:     public bool IsValid
  18:     {
  19:         get
  20:         {
  21:             return Validator.Validate(this).IsValid;
  22:         }
  23:     }
  25:     public IList<ValidationFailure> ValidationErrors
  26:     {
  27:         get
  28:         {
  29:             return Validator.Validate(this).Errors;
  30:         }
  31:     }
  32: }

The key here is the “Validator” property. This does all the work for all models. Each model will now have an “IsValid” property and a “ValidationErrors” property. These two properties use the private “validator” property to get the type of validator it needs and pass in the object to validate. On line 11 you will see that the ValidationFactory.GetValidator method is called. The base ValidatorFactoryBase does most this work for us. The key here is that on line 11 we use the UnderlyingSystemType of the object. In this case the “Car” class. The factory then uses the SimpeIoC to find the right validator for that class. Now on line 21 and 29 I just call the methods I want on the Validator property. The “Validate” method requires the object to validate to be passed in. This is also easily obstructed by just passing “this” (the current model that is built on top of the ModelBase) into the call.

Just like that I can now do the following in my ViewModel (which holds a property of Car for my new Car model object).

   1: private void SaveCar()
   2: {
   3:     if (this.Car.IsValid)
   4:     {
   5:         _CarProvider.SaveCar(this.Car);
   7:         _NavService.NavigateTo(ViewModelLocator.MyProfilePage);
   8:     }
   9:     else
  10:         base.DisplayValidationErrors(this.Car.ValidationErrors);
  12: }

On line 3 I simple call “IsValid” on the model I have bound to the view. You could also now wire that up to a commands “CanExecute” method as well. Hats off to the Fluent Validation team, it is a slick module easy to plug into and very powerful.


NOTE: If you are curious about the “NavigationService” checkout this blog. It does a great job enabled the standard Windows Phone NavigationService in an MVVM architecture.


Илья Колесников said...

Thats cool:) But what about DisplayValidationErrors() method? I want highlight invalid properties "like ASP MVC". I looking for a solution without adding properties like "IsCustomerNameValid" and setup individual bindings for each property. What is xaml look like in your case?

sorry for my english

KarmaEDV said...

Hi and thank you very much, didn't know Fluent Validation.

To make this post complete you could include the implementation of DisplayValidationErrors from your ModelBase and also how you use it in you controls in the view.


Unknown said...

That's great! thank you!
But i run into problem when i want to do some extra
validation like check whether attribute is unique.
Before that i was passing collection of objects to validator through
constructor. Any ideas how to solve that?

Anonymous said...

How do you plan on unit testing this? One of the main benefits in decoupling the logic from the presentation by using MVVM is unit test-ability. By coupling your models to a service locator, kind of breaks that entirely.

Would it not be better to inject the validation factory into the view model and couple the validation concerns to that instead of the model?

I like the fluent validation aspect, good library.