I'm trying to restrict all characters other than English alphabets, but I'm still able to enter some naughty characters which is not good! How can I prevent that. These naughty characters not caught by my regex are - _ + = ? < > '
.
private void AlphaOnlyTextBox_OnKeyDown(object sender, KeyEventArgs e)
{
var restrictedChars = new Regex(@"[^a-zA-Z\s]");
var match = restrictedChars.Match(e.Key.ToString());
// Check for a naughty character in the KeyDown event.
if (match.Success)
{
// Stop the character from being entered into the control since it is illegal.
e.Handled = true;
}
}
<Window x:Class="WpfApplication4.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBox Height="21"
Width="77"
MaxLength="2"
KeyDown="AlphaOnlyTextBox_OnKeyDown"
>
</TextBox>
</Grid>
</Window>