String Filter: Detect non-ASCII characters

I am creating an application that will send an input string to a mobile device. Some devices have problems encoding special characters, so I would like to create a filter that prevents the user from entering special characters on the PC.

The application is written in C # (.NET 3.5), and I would like to add a method for pressing a key. The pseudocode is as follows:

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 the ASCII / non-ASCII character so that it can be used in state

Does txtEntry.Text contain a non-ASCII character?

Thanks!

+4
string encoding
source share
3 answers

Well, you can do:

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

I'm not sure if you really want to just delete the last character you entered - consider trimming and pasting the whole line without ascii ...

+5
source share

I assume that you need ASCII for printing, not just ASCII, so you probably want to limit yourself to 0x20 points through 0x7e:

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

But I'm not sure if the message box is the right way. This can be very annoying. It might be better to have error control in your form somewhere that you can simply set an error message (and give it a signal) when the user enters an invalid character. When the user enters another (valid) character, reset, which controls the empty string. It seems much less intrusive.

+4
source share

This is a regular expression parameter (using System.Text.RegularExpressions )

  string s = "søme string"; bool result = Regex.IsMatch(s, @".*[^\u0000-\u007F].*"); // result == true 
+2
source share

All Articles