简体   繁体   中英

Validate user input using C# RegularExpressions

How to Validate numerical input, max length limited 3 and should not start with zero characters (010, 001 should invalidate). I used C# regex.IsMatch() with following regex ([1-9]|[1-9][0-9]|[1-9][0-9][0-9])* . But it validating inputs start with zeros. How to resolve this..?

You can omit the alternations by repeating a character class 0 - 2 times and you should use anchors to assert the start ^ and the end $ of the string.

^[1-9][0-9]{0,2}$
  • ^ Start of string
  • [1-9] Match a digit 1-9
  • [0-9]{0,2} Match 0, 1 or 2 times a digit 0-9
  • $ Assert end of the string

Usage:

bool isMatch = Regex.IsMatch("100", @"^[1-9][0-9]{0,2}$");

Regex demo

Regex are great sure. Note that you could achieve this easily without any regex:

static bool IsValid(string input)
{
    return !string.IsNullOrEmpty(input)
        && input.Length < 3 && !input.StartsWith("0") && input.All(char.IsDigit); 
}

Try it online

I'd be more specific with this one:

^((?!(0))[0-9]{0,3})$ 

Explanations:

  • 1st one is not 0 & i want maximum 3 digits between 0 and 9.

[1-9][0-9]{2}$

This would work as per your requirement. testes on regex buddy with following test cases

  1. 001 Fail
  2. 1000000 Fail
  3. 900 Pass
  4. 010 fail

您可以使用^[1-9][0-9]{0,2}$ ,不允许以零开头

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM