Introduction to 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


http://www.c-sharpcorner.com/UploadFile/91c28d/data-input-validation-in-wpf-part-1-validation-with-except/Images/WPF.jpg

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

public partial class ValidationWithException : UserControl, INotifyPropertyChanged 
    
        public ValidationWithException() 
        
            InitializeComponent(); 
        
        #region INotifyPropertyChanged Members 
   
        public event PropertyChangedEventHandler PropertyChanged; 
        public void OnPropertyChanged(string txt) 
        
   
            PropertyChangedEventHandler handle = PropertyChanged; 
            if (handle != null
            
                handle(this, new PropertyChangedEventArgs(txt)); 
            
        
        #endregion 
        private int accountNumber; 
   
        public int AccountNumber 
        
            get { return accountNumber; } 
            set { accountNumber = value; } 
        
   
        private string zipCode; 
   
        public string ZipCode 
        
            get { return zipCode; } 
            set
                if (zipCode != value) 
                
                    ValidateZipCode(value); 
                    zipCode = value; 
                    OnPropertyChanged("ZipCode"); 
                
               
            
        
        private void ValidateZipCode(string value) 
        
            if (!string.IsNullOrEmpty(value) && value.Length < 5) 
            
                throw new ArgumentException("Invalid Zip Code"); 
            
        
           
    }

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.

http://www.c-sharpcorner.com/UploadFile/91c28d/data-input-validation-in-wpf-part-1-validation-with-except/Images/WPF1.jpg
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.

See Also


How to: Implement Binding Validation
INotifyDataErrorInfo Interface