Data Input Validation In WPF Part 1 : Validation With Exception

Validation with Exception

Validating from exceptions is one of the simplest validation mechanisms for WPF. Normally the binding of catch exceptions are thrown by get/set blocks of bound properties. This mechanism will throw an exception when we get incorrect data.

ValidatesOnExceptions will indicate the error on the control if a get/set block throws an exception.

Demo



We have two TextBoxes for account number and Zip code, you can see ValidatesOnExceptions=True in the Zip code binding.

  1. public partial class ValidationWithException : UserControl, INotifyPropertyChanged  
  2.     {  
  3.         public ValidationWithException()  
  4.         {  
  5.             InitializeComponent();  
  6.         }  
  7.         #region INotifyPropertyChanged Members  
  8.   
  9.         public event PropertyChangedEventHandler PropertyChanged;  
  10.         public void OnPropertyChanged(string txt)  
  11.         {  
  12.   
  13.             PropertyChangedEventHandler handle = PropertyChanged;  
  14.             if (handle != null)  
  15.             {  
  16.                 handle(thisnew PropertyChangedEventArgs(txt));  
  17.             }  
  18.         }  
  19.         #endregion  
  20.         private int accountNumber;  
  21.   
  22.         public int AccountNumber  
  23.         {  
  24.             get { return accountNumber; }  
  25.             set { accountNumber = value; }  
  26.         }  
  27.   
  28.         private string zipCode;  
  29.   
  30.         public string ZipCode  
  31.         {  
  32.             get { return zipCode; }  
  33.             set {  
  34.                 if (zipCode != value)  
  35.                 {  
  36.                     ValidateZipCode(value);  
  37.                     zipCode = value;  
  38.                     OnPropertyChanged("ZipCode");  
  39.                 }  
  40.               
  41.             }  
  42.         }  
  43.         private void ValidateZipCode(string value)  
  44.         {  
  45.             if (!string.IsNullOrEmpty(value) && value.Length < 5)  
  46.             {  
  47.                 throw new ArgumentException("Invalid Zip Code");  
  48.             }  
  49.         }  
  50.           
  51.     } 

In the class file we have one method, validateZipCode, that will check the length of the Zip code. If the Zip code length is less than 5 then it will throw an ArgumentException. We will call this method before setting the Zip code value in the set block. One of the advantages of using this is you can prevent an incorrect value before setting.

Run the application. Type something such as a Zip code and press the Tab key.


Now you can see the Red box on the control. WPF controls have a built-in error template that simply puts a Red box around the control.

Up Next
    Ebook Download
    View all
    Learn
    View all