Validate from 1 to 6 digits, the first of which cannot be zero

Asked

Viewed 44 times

4

How is regex to validate the following rule:

  1. Numbers only;
  2. A maximum of 6 numbers, and a minimum of 1;
  3. The first number needs to be different from 0;

I tried it this way and it didn’t work:

/^[1-9]+(\d){0,5}$/

What’s the mistake?

1 answer

4


The problem is in + in [1-9]+.

The quantifier + means "one or more occurrences", therefore [1-9]+ takes one or more occurrences of digits from 1 to 9.

If you want exactly one digit of 1 to 9, just remove the +:

/^[1-9]\d{0,5}$/

And also note that you don’t need parentheses around the \d, therefore, \d{0,5} already taken from zero to five digits of 0 to 9.


How was not said which language/engine/tool you are using, I think it is worth mentioning that the shortcut \d, depending on the language/engine/tool, can also consider any character of the Unicode category "Number, Decimal Digit". This includes not only the digits of 0 to 9, but also several other characters representing digits, such as ٢ (ARABIC-INDIC DIGIT TWO), among others.

If the idea is to ensure only digits of 0 to 9, can change to:

/^[1-9][0-9]{0,5}$/

But of course if you’re wearing one engine in which \d is equivalent to [0-9] (or if you know that your data will never have the other characters already cited), then either use one or the other.

  • 1

    It worked, thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.