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 va开发者_运维百科lid.
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".
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
精彩评论