Share via


WPF: ValidationRules


Overview

ValidationRules is a class, which provides a way to create a custom rule in order to check the validity of a user input. These ValidationRules are specific to WPF, they did not get carried over to Silverlight, Windows phone or Windows 8 XAML technologies.

What you do is define a class that inherits from a ValidationRule base class, and then you override a validate method that’s an abstract method in the base class. That Validate method returns a ValidationResult Object, which includes a flag to indicate success or failure, a Boolean, and an error message that can be associated with it. Once you have the ValidationRule defined, you go and you hook it up to a ValidationRules collection that’s on a binding.

Demo

Create a WPF application. Create a class that implements ValidationRule and override the Validate method. Here you can write the validation rule for your application. Give a regular expression to validate email id.

public class  RegexValidation : ValidationRule
   {
       public override  ValidationResult Validate(object value, CultureInfo cultureInfo)
       {
           Regex regex = new  Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
           Match match = regex.Match(value.ToString());
           if (match == null || match == Match.Empty)
           {
               return new  ValidationResult(false, "Please enter valid email");
           }
           else
           {
               return ValidationResult.ValidResult;
           }
       }
   }

Inside MainWindow class, create one property

public partial  class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private string  email;
  
        public string  Email
        {
            get { return email; }
            set { email = value; }
        }
  
    }

In XAML, Bind the property and specify the validation rule here.

<StackPanel>
            <TextBox Margin="5" Height="30"
  
                     Width="200" >
                <TextBox.Text>
                    <Binding Path="Email" ElementName="thiswindow" >
                        <Binding.ValidationRules>
                            <local:RegexValidation></local:RegexValidation>
                        </Binding.ValidationRules>
                    </Binding>
                </TextBox.Text>
            </TextBox>
            <TextBox Margin="5" Height="30" Width="200" ></TextBox>
        </StackPanel>

Run the application and type any invalid email address and hit enter, you can see a red box on the email address textbox. This is coming from our regular expression validation.

See Also

Data Input Validation In WPF : Validation With Exception