How to set regular expression in TextBox?

How to set regex on WPF TextBox? I want the text field to accept input in some kind of predefined format. Is it possible?

+5
source share
2 answers

You have several options:

  • You can create a subclass ValidationRule(see below) and add it to the Binding Validators Properties property
  • You can set ValidationCallbackbound to your property, throw an exception if the value is incorrect, and use this technique to easily show validation errors.
  • , TextBox.TextChanged
  • TextBox TextBox_Changed
  • PreviewKeyDown PreviewTextInput ,
  • , Jan

WPF bound. PreviewKeyDown/PreviewTextInput .

ValidationRule:

public class RegexValidationRule : ValidationRule
{
  ... // Declare Regex property and Message property

  public override ValidationResult Validate(object value, CultureInfo cultureInfo)
  {
    if(Regex.IsMatch((string)value))
      return ValidationResult.ValidResult;
    else
      return new ValidationResult(false, Message);
  }
}
+7

, , .

0

All Articles