Thursday, July 5, 2012

Data Validation in WPF

When it comes to Data Validation most of us use the old mechanism of inspecting the key press. What can can you do If you want the user to enter only values in a specified range for a text box ??? One of the old mechanisms are to check the entered value at a button click event to save the record. Thanks to WPF Validation rules, we can make the work more easier and create cleaner code. The steps of implementing Validation rules will be further explained using an example where you need to validate a Person's age as for the following conditions,

- Age > Min age
- Age < Max age
- Age should only be numeric.

Follow the below steps to implement.

1) Create a WPF project and Add a class (I've used 'AgeRangeValidation' as the name).
2) Bring System.Windows.Controls namespace into scope.
3) Inherit from the ValidationRule class and implement the abstract method Validate
4) Add Automatic properties to set the Min and Max ages.
5) Add code as follows to validate for non numeric characters and age against the specified range.


6) Create a simple UI containing components to validate. In this example I've used two text boxes and a button.

7) Download the File containing in the following link and Add code to the XAML file of the UI you created using the attachment as a guidance.

After adding the code to the XAML file of the UI, the fields will be validated as the following screen shots.


1 comment: