2

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>
Vahid
  • 5,144
  • 13
  • 70
  • 146
  • The regex seems to catch those (as tested on regexr.com). Are you sure the problem isn't elsewhere? – rtmh Jul 11 '16 at 18:04
  • Yes, the problem [must be somewhere else](http://regexstorm.net/tester?p=%5b%5ea-zA-Z%5cs%5d&i=-+_+%2b+%3d+%3f+%3c+%3e+%27). – Wiktor Stribiżew Jul 11 '16 at 18:05
  • @rtmh You can build the question easily in WPF/C#. It doesn't work for some odd reason! – Vahid Jul 11 '16 at 18:07
  • @rtmh One suggestion! Maybe it has something to do with pressing the Shift button! Because we need to press that to enter +? – Vahid Jul 11 '16 at 18:11
  • I wouldn't say we can build it *easily*. As for that issue, look into the specifics of the KeyEventArgs::Key functions, does it return what you expect? – rtmh Jul 11 '16 at 18:13
  • Indeed the Key object seems to represent only a single key so you are right about the area of your problem. I am unfamiliar with the environment you are using, but I suspect there is a method for character input checking, if not as a feature of the API, then as a best practice that you may be able to find on SO. – rtmh Jul 11 '16 at 18:18
  • Are you looking to handle a KeyPress Event instead perhaps? – rtmh Jul 11 '16 at 18:23
  • I just updated the question with XAML code. – Vahid Jul 11 '16 at 18:31
  • Honestly I was half way through an answer but couldn't figure out the MSDN documentation in time. These pages might be helpful, however: [first](https://msdn.microsoft.com/en-us/library/ms171549(v=vs.110).aspx), [second](https://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress(v=vs.110).aspx), [third](https://msdn.microsoft.com/en-us/library/system.windows.forms.control.keydown(v=vs.110).aspx) – rtmh Jul 11 '16 at 18:32
  • I am not sure, but perhaps, [this one](http://stackoverflow.com/questions/1458748/wpf-onkeydown-not-being-called-for-space-key-in-control-derived-from-wpf-text) is related. – Wiktor Stribiżew Jul 11 '16 at 18:32
  • @rtmh Thanks, I couldn't find a KeyPress event in WPF. – Vahid Jul 11 '16 at 18:33
  • `@"^[a-zA-Z]+$"` should work. It assumes the Latin Alphabet. Taken from: http://stackoverflow.com/questions/1181419/verifying-that-a-string-contains-only-letters-in-c-sharp – Adam Jul 11 '16 at 18:36
  • @rtmh Found the solution. – Vahid Jul 11 '16 at 18:51

2 Answers2

2

Try this expression:

var restrictedChars = new Regex(@"[^(\W_0-9)]+");

It will exclude everything but large and small letter characters (not depending on a spceific language).

Hope it helps!

Itay Podhajcer
  • 2,616
  • 2
  • 9
  • 14
2

After so much head-scratching I realized that for some reasons unknown to me, KeyDown event doesn't capture certain characters, but PreviewTextInput does!

    private void UIElement_OnPreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        var restrictedChars = new Regex(@"[^a-zA-Z\s]");

        var match = restrictedChars.Match(e.Text);

        // 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;
        }
    }

    <TextBox Height="21"
             Width="77" 
             MaxLength="2"
             PreviewTextInput="UIElement_OnPreviewTextInput"
                                       >
    </TextBox>

If you also want to disable Space button:

    <TextBox Height="21"
             Width="77" 
             MaxLength="2"
             PreviewTextInput="UIElement_OnPreviewTextInput"
             PreviewKeyDown="UIElement_OnKeyDown"
                                       >
    </TextBox>

    private void UIElement_OnKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Space)
        {
            e.Handled = true;
        }
    }
Vahid
  • 5,144
  • 13
  • 70
  • 146