tags:

views:

89

answers:

2

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.

+2  A: 

Try:

@"^[A-Z0-9/-]*$"

Or if you need to limit the number of characters:

@"^[A-Z0-9/-]{lowerbound,upperbound}$"

Edit: Added start and end anchors

Falle1234
This only checks whether those characters exist, not whether characters which aren't in the set exist.
jwsample
yeah your right. I should have added start and end anchors
Falle1234
Both this and jwsample's answer work correctly, but I prefer this just because I like that "from the start to the end all characters are in this range of allowed chars" to my mind is closer to the intent than the double negative of "does not contain a character that is not in this range". Logically the same thing of course.
Jon Hanna
+3  A: 

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".

jwsample
Thanks this is the solution I went with. Once you get your mind in to checking for what is not allowed vs. what is allowed its simple.
BENBUN Coder