开发者

String validation in .NET

开发者 https://www.devze.com 2023-01-10 22:06 出处:网络
String validation .. I want to validate a string contains only the following characters : A-Z 0-9 \"/\" \"-\"

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

0

精彩评论

暂无评论...
验证码 换一张
取 消