Question

I'm converting one of my existing applications to the MVVM pattern to improve its structure and I'm a bit torn on what would be the best way to do the data validation.

Currently the application uses data binding to link the UI and code and uses a few validation rules and value converters which can be reused on similar values (one of each for dates, etc.).

Whilst reading up on MVVM I've come across IDataErrorInfo, which I find attractive because it would keep validation out of the view, thus slightly reducing repetitive code when setting bindings, etc. and allow for more specific error messages.

ValidationRules on the other hand block the transfer of binding data if the validation fails, which I need because I only want the model values to change a new, valid value is supplied.

My major concern is that if I restrict things too much in the viewmodel that this will make things difficult in the view - is it a good idea to restrict things to a comfortable level in the general case and then remedy specific cases that need more flexibility in the view?

So my main question is, would it be better to put validation and conversion in the properties of the viewmodel or stick with my validationrules and valueconverters (or some compromise in between)?

Was it helpful?

Solution

I implement all validation in the view model, using IDataErrorInfo, and let the view model decide whether or not it should pass property changes to the model based on whether the property is valid. So a typical setter looks something like:

public string Value
{
   set
   {
      if (value == _Value)
      {
         return;
      }
      _Value = value;
      Validate("Value");
      if (Error["Value"] == null)
      {
         Model.Value = value;
      }
      OnPropertyChanged("Value");
   }
}

I never, ever implement validation or value conversion in the view. That just seems like begging for trouble.

OTHER TIPS

I would use a combination.

I use Idataerrorinfo in my entities (validation is not in the viewmodel) for core re-usable business rules. My entities can also validate themselves this way.

I then use view ValidationRules for places where a binding error will not make it to my entity such as when a string is used as input in a integer textbox.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top