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
  • 3
    You're not using RegExp correctly. Show the code and people will be able to point out the error. Commented Aug 8, 2010 at 21:06
  • Your probably missing start/end anchors in your regular expression. Commented Aug 8, 2010 at 21:09

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

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

2 Comments

This only checks whether those characters exist, not whether characters which aren't in the set exist.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.