stackover man
stackover man

Reputation: 13

Javascript regex for number check and maximum length of 3 and does not start with 0

Currently I am trying to find a regular expression, that does the following

1) checks number

2) Allows max length of 3

3) Does not start with 0

I have the following regex which works fine

^[0-9]{1,3}$

Above regular expression allows only numbers that have maximum 3 digits but I am not sure how to prevent 0 in the beginning.

code

var numericRegex = new RegExp("^[1-9][0-9]{0,2}$");
numericRegex.test(123) //false

Let me know what I am missing

Thanks

Upvotes: 1

Views: 733

Answers (3)

Sekny
Sekny

Reputation: 11

Shortest regex is should be

^[1-9]{1}\d{2}$

Upvotes: 0

Adrian May
Adrian May

Reputation: 2182

Try it like this:

^[1-9][0-9]?[0-9]?$ 

or:

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

In node.js it can be used like this:

> "123".match(/^[1-9][0-9]{0,2}$/)
[ '123', index: 0, input: '123' ]
> "023".match(/^[1-9][0-9]{0,2}$/)
null
> "123".match(/^[1-9][0-9]?[0-9]?$/)
[ '123', index: 0, input: '123' ]
> "023".match(/^[1-9][0-9]?[0-9]?$/)
null

And the other answer is also fine:

> "123".match(/^(?!0)\d{1,3}$/)
[ '123', index: 0, input: '123' ]
> "023".match(/^(?!0)\d{1,3}$/)
null

Upvotes: 2

user557597
user557597

Reputation:

Or could be done with

^(?!0)\d{1,3}$

Upvotes: 2

Related Questions