I want to ensure certain input into my webapp contains only characters that can represented as ascii (it’s for tagging and I’m trying to save space in the database column by using varchar instead of nvarchar)
Is there a framework feature to do this in .net or should I check the character codes one by one to ensure they’re in the correct range?
EDIT: I just wrote this extension method but it seems too cumbersome for something so simple.
public static bool IsAscii(this string value) { if (value != null) for (int current = 0; current < value.Length; current++) { if ((int)value[current] > 127) return false; } return true; }
Given that you’re using an extension method, you’re presumably using C# 3 and .NET 3.5. In that case I’d use:
This will check that every character is in the range [U+0020-U+007E] which only contains printable characters. Is that what you’re after?
As other comments have said, that will exclude everything with accents etc – are you sure that’s okay? This also rejects carriage return, linefeed and tab. Again, is that all right?