How can I set a regular expression on WPF TextBox? I want the textbox to accept input in some predefined format. Is it possible?
You have several options:
ValidationRule
subclass (see below) and add it to your Binding's Validators propertyValidationCallback
on your bound property, throw an exception if the value is wrong, and use this technique for easily showing validation errorsFor arbitrary regexes I would generally use WPF's built-in validation features or do the validation on the bound property. For specific needs the PreviewKeyDown/PreviewTextInput or masked text box might be better.
Here is how you would create a ValidationRule subclass:
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With