Every application needs validation. However, in WPF it still costs too much effort to implement it.
For instance, an ErrorProvider like in Winforms is not supported.
There are several conditions my validation should satisfy:
* I want to be able to specify validation in the data object. I consider this to be business logic and in this way, all errors are catched.
* It should be easy to check whether or not the object is valid; this to support enabling/disabling commands.
* I want a list of validation errors.
I’ve chosen to use the Validation Application Block of the Enterprise Library 5. It has many advantages:
* It has a lot of built-in validators
* You can use attributes
* You can specify your own custom validators (and use these in attributes)
* You can store validation rules in configuration files (using a designer)
When you only need validation on single properties, the data annotations are very clean.
For more complex validation rules, you can use the self-validation feature.
To implement this, you need to:
* add the HasSelfValidation attribute to the class
* add a void method that accepts a single ValidationResults input param, and decorate it with a SelfValidation attribute
The end result of my business entity:
[HasSelfValidation]
public class Person
{
[StringLengthValidator(7, MessageTemplate="FirstName is too long")]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[SelfValidation]
public void Check(VAB.ValidationResults results)
{
if (FirstName != "Jowen" || LastName != "Mei")
results.AddResult(new VAB.ValidationResult("Name is not Jowen Mei", this, "", "", null));
}
}
Check out my example to see it in action!
I’ve made a simple ValidationSummary control which displays the error messages.
Note: due to this bug I can’t modify the assembly references as usual. So you have to have Enterprise Library installed!

