A while ago, WPF guru Josh Smith blogged about using the ViewModel to provide a first line of defence when validating data using the MVVM model. In his article, Josh talks about having the ViewModel perform some validation before passing this back to the underlying model. In his example, he uses a
string property to perform initial validation on a UI element before it updates an integer, so that the user can type in abc123, but the model only gets updated if it's a valid number. Please read his article here for more information.
While I liked Josh’s implementation, there was something nagging at me - his implementation relied heavily on
switch statements in the property validation, and this really goes against the grain for me. Thinking about this for a while, it seemed to me that we could achieve a similar implementation and, at the same time, provide a nice level of abstraction. To do this, we can use the Action<T> delegate to nicely decouple the validation from the actual property validation. The following class provides the underlying mechanism for separating the validation.
Now, both the
Model classes can derive from this class and get access to the same functionality. The following class demonstrates this:
The interesting bit of this class is how simple the implementation of
IDataErrorInfo here actually is. All the “magic” has been taken care of by creating an Action that will invoke the
ValidateAge method. By calling
AddValidation on the base class and passing the name of the property that the validation applies to, we can automatically hook up to perform the validation.
You can download the sample project here. Be sure to change the extension back from Doc to Zip and then decompress it.