WPF Reflections:

Validation

Mar 31 2008   11:03PM GMT

Data validation in WPF, my approach



Posted by: Mark Shurmer
WPF, Databinding, XAML, Validation

Whether to use IDataErrorInfo or ValidationRule - that is the question, as I posed in a previous post.

So , you may be wondering what do I do in my WPF projects?
Or you may not :-)

Well, I tend to use both!
I use IDataErrorInfo to provide validation in the business object itself, then derive extra classes from ValidationRule when I want validation across different business objects.

I have tried making the Validation classes always separate from the pure data business classes, but I found it to be counter productive and also counter intuitive.

Mar 31 2008   11:01PM GMT

Data validation in WPF using ValidationRule



Posted by: Mark Shurmer
Validation, Databinding, WPF, XAML, Microsoft Windows, Windows Computing

As I mentioned in a previous post, you can specify validation by creating a Validation class (or classes).

You do this by deriving a new class from the ValidationRule class and overriding the Validate method.

Why would you do this, instead of implementing IDataErrorInfo?
Well, if you wanted to do validation across a number of objects, then this is the way to go.
It also provides a level of separation from your business objects, leaving them to deal with business data and the validation objects to deal with validation.
A downside is that it is not backwardly compatible with WinForms :-(

How do you tell your xaml to use it? By specifying it in the ValidationRules element of your binding - just like IDataErrorInfo.


Mar 14 2008   4:50PM GMT

Validation



Posted by: Mark Shurmer
WPF, XAML, Validation

There seems to be four ways to go with validation with WPF:

  1. Use IDataErrorInfo
  2. Use custom classes with ValidationRule
  3. Combine 1 and 2
  4. Roll your own

What do I mean by each of these, and why?

  1. Use IDataErrorInfo. You canimplement this interface in your business objects and you get the opportunity to specify validation for each property or for all properties. You do this in (usually) a general purpose method that does validation for all of your properties in your business object. This is good if you need validation for a business object, but not across objects. You can tell wpf to use it (in v3.5) by specifying ValidatesOnDataErrors=”True” in your binding specification.
  2. Inherit a class from ValidationRule, and provide an override for the Validate method. You could do this for either a particular business object, or across a number of objects. You can use it in xaml by specifying it in the binding’s ValidationRules collection.
  3. Do 1 for business object validation, and 2 for any validation that needs to be done across business objects
  4. Do this when you need to extend the validation, e.g. like in the CSLA.Net framework