Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string filter: detect non-ASCII signs

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!

like image 853
Niko Gamulin Avatar asked Dec 17 '22 03:12

Niko Gamulin


2 Answers

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...

like image 57
Jon Skeet Avatar answered Jan 13 '23 22:01

Jon Skeet


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.

like image 45
paxdiablo Avatar answered Jan 13 '23 22:01

paxdiablo