I am trying to make text box accept only specific characters.
My TextBox is bound to the following:
private string _CompanyID;
public string
I do this with the PreviewtextInput event. I have a generic event used for multiple TextBoxes which takes the regex from a configuration table, but I have hard-coded the regex in this example.
private void GenericTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = !IsTextAllowed(e.Text, @"[^a-zA-Z]");
}
private static bool IsTextAllowed(string Text, string AllowedRegex)
{
try
{
var regex = new Regex(AllowedRegex);
return !regex.IsMatch(Text);
}
catch
{
return true;
}
}