Wednesday, July 29, 2009

Checking for illegal characters in C#

I was dealing with windows forms application and wanted to check for illegal characters. So i came up with this small function and thought of sharing it for anybody to use it:
 private bool CheckIllegalChars(string nametext)  
 {  
 char[] illegalChars = new char[] { '*', '|', ',', '\\', '\"', '<', '>', '[', ']', '{', '}', '`', '\'', ';',':', '(', ')', '@', '&', '$', '#', '%', '?', '^' };  
 int length = nametext.Length;  
 bool res = false;  
 if (nametext.IndexOfAny(illegalChars) > -1)  
 {  
 MessageBox.Show("The textbox cannot contain illegal characters");  
 res = true;  
 }  
 return res;  
 }  

2 comments:

purgatory said...

which one is the "." key? cause i need to allow it in my syntax.

smcube said...

Sorry for the delay. "." isn't being checked here.