Click here to Skip to main content
Click here to Skip to main content

Tagged as

Action Based ViewModel and Model Validation

, 16 Apr 2009
Rate this:
Please Sign up or sign in to vote.
Action based ViewModel and Model Validation

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.

ModelBase class

Now, both the ViewModel and Model classes can derive from this class and get access to the same functionality. The following class demonstrates this:

Person class

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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Pete O'Hanlon
CEO
United Kingdom United Kingdom
A developer for over 30 years, I've been lucky enough to write articles and applications for Code Project as well as the Intel Ultimate Coder - Going Perceptual challenge. I live in the North East of England with 2 wonderful daughters and a wonderful wife.
 
I am not the Stig, but I do wish I had Lotus Tuned Suspension.
Follow on   Twitter   Google+

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web02 | 2.8.140902.1 | Last Updated 16 Apr 2009
Article Copyright 2009 by Pete O'Hanlon
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid