views:

414

answers:

3

Hi,

I am creating an application which will send the input string to mobile device. Some devices have problems with encoding special characters so I would like to create a filter which doesn't allow the user on PC to enter special characters.

The application is written in C# (.NET 3.5) and I would like to attach a method to key press event. The pseudocode is the following:

private void checkTextBoxContent(TextBox txtEntry)
{
    if(txtEntry.Text contains non-ASCII sign)
    {
        show messageBox;
        remove the last entered character;
    }
}

Does anyone know if there is any existing method that detects ASCII/non-ASCII sign so that could be used in condition

txtEntry.Text contains non-ASCII sign?

Thank you!

+2  A: 

This is a regex option (using System.Text.RegularExpressions)

    string s = "søme string";
    bool result = Regex.IsMatch(s, @".*[^\u0000-\u007F].*"); // result == true
serhio
Doesn't get much simpler than that.
JohnE
You probably don't want to send \u0000 to a mobile either. And I won der how much would be lost if you discarded `\u0001-\u0008`, `\u000b`, `\u000c` and `\u000f-\u001f` too. `\u0009` (TAB), `\u000a` (CR) and `\u000d` (LF) are the only reasonable ASCII control chars.
MSalters
+2  A: 

Well you can do:

public static bool IsAllAscii(string text)
{
    return text.All(c => c >= ' ' && c <= '~');
}

I'm not sure you would really want to just remove the last character entered though - consider cutting and pasting a whole non-ascii string...

Jon Skeet
A: 

I'm assuming you need printable ASCII rather than just ASCII, so you'd probably want to limit yourself to the 0x20 thru 0x7e code points:

if (Regex.isMatch (str, @"[^\u0020-\u007E]", RegexOptions.None)) {
    ... Show message box here ...
    str = Regex.Replace (str, @"[^\u0020-\u007E]", string.Empty);
}

But I'm not convinced a message box is the right way to go. That could get very annoying. It may be better to have an error control on your form somewhere that you can just set to an error message (and beep to let them know) when the user enters an invalid character. When the user enters another (valid) character, reset that control to an empty string. That seems far less obtrusive.

paxdiablo