1

I want to limit the matches to 7 digits at most, but at the same time I want to allow zeroes in front of the number. Right now it's allowing numbers such as 0, 1, 12, 123, 1234, 12345, 123456, 1234567 which is expected. This is the problem, I also want to find a match for numbers such as 0001234567 but not 12345678. This is the regex I'm using:

/^[1-9][0-9]{0,6}$|^0$/g

3 Answers 3

3

Try this /^0*[0-9]{7}$/

  • 0001234567 - pass
  • 1234567 - pass
  • 12345678 - error
  • 12345 - error
Sign up to request clarification or add additional context in comments.

3 Comments

[0-9] => \d. Both work, the latter is perhaps somewhat more idiomatic.
Sadly, the OP meant up to seven digits, not exactly. (I read it as exactly too.)
i'm sorry if my question wasn't clear. i updated the question already for future reference. you still have my upvote
2

This should do it:

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

It allows any number of leading zeroes.

2 Comments

@Simon - I thought you wanted to match exactly seven digits (plus any number of leading zeros). That's what your question seems to say. Did you mean up to seven digits?
@T.J.Crowder i meant up to seven digits
1

As you als want to match 0, you might also use an alternation to match 1+ more zeroes as well

^(?:0*[1-9]\d{0,6}|0+)$

Regex demo

You might also use parseInt and check for the string length

const limitNumbers = s => parseInt(s, 10).toString().length < 8;
const strings = [
  "0",
  "1",
  "12",
  "123",
  "1234",
  "12345",
  "123456",
  "1234567",
  "0001234567",
  "12345678",
];

strings.forEach(s => console.log(`${s}: ${limitNumbers(s)}`))

Comments

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.