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;  
 }