Tutorial :String validation in .NET


String validation ..

I want to validate a string contains only the following characters :

  • A-Z
  • 0-9
  • "/"
  • "-"

What's the best way to achieve this. I have tried to use a REGEXP but this is returning valid if any of the characters are valid, not if all of the characters are valid.


You could negate using [^A-Z0-9/-]. If it matches you know there are invalid characters.

if (Regex.IsMatch("input",@"[^A-Z0-9/-]"))  {     //invalid character found  }  

The character ^ inside the bracket negates the set, meaning "find anything thats not here".




Or if you need to limit the number of characters:


Edit: Added start and end anchors

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »