IValidator and RIA Services Model Objects

Topics: Questions
Jul 17, 2012 at 5:06 PM

I have a Silverlight and RIA Services application that uses a TabControl and nested view models on each tab.  As you know, a TabControl loads only the tab that's visible and unloads it when the selected tab switches.  This presents a problem for validation because each view model is responsible for validating its respective piece of the model object to which they are all bound but some of them will never be loaded.

It doesn't feel correct to have the DataWindowViewModel take on responsibility for validating the whole model so I'm looking at moving all validation into an IValidator object and registering an IValidatorProvider service implementation.

Since our model objects do not inherit from DataObjectBase we can't directly associate them with IValidator objects and the IValidatorProvider service is called only for view models.  What's the proper solution for this?

I considered implementing ValidateFields() and ValidateBusinessRules() in each view model and have their implementation fetch the IValidator object for the model object like this:

protected override void ValidateFields( List<IFieldValidationResult> validationResults )
    IValidator validator = GetService<IValidatorProvider>().GetValidator( model.GetType() );

    validator.ValidateFields( model, validationResults );

Is this a reasonable approach or do I have it all wrong? 

Jul 18, 2012 at 2:45 PM
Edited Jul 18, 2012 at 3:11 PM

Your issue is related with a design decision Model vs. ViewModel base validation.

From my point of view ViewModel base validation is more flexible and works at the same level of abstraction of the MVVM pattern.

For instance you could display with diferent view of the same model implementing the right viewmodel for each view, therefore you could validate in diferent ways your model implementing the right validator for your viewmodel.

If you have to write the DataWindowViewModel for your DataWindow then the DataWindowViewModel should be responsible of validate it self or should exists external validators "in-charge" to validate it.

You are able to write your own validator and validator providers. We have built-in support to write external validators with fluentvalidation using ViewModel base validation approach.