Max 3 digits, up to 3 decimals

11.7k views Asked by At

It seems I'm stuck again with a simple regex.

What I'd like:

  • A number between 1 and 999
  • Optional: a comma , sign
  • If the comma sign is entered, minimum 1 decimal and maximum 3 decimals should be presebt.

Allowed:
100
999,0
999,999
999,99

Disallowed:
-1
0
999,
999,9999

This is what I have so far:

^[0-9]{1,3}(?:\,[0-9]{1,3})?$

Any tips?

2

There are 2 answers

5
anubhava On BEST ANSWER

You can use this regex:

/^[1-9]\d{0,2}(?:\,\d{1,3})?$/

RegEx Demo

Main difference from OP's regex is use of [1-9] which matches digits 1 to 9 before rest of the regex.

4
Michel Antoine On

This regex should work :

^[1-9]\d{0,2}(?:,\d{1,3})?$

Here is the explanation :

^[1-9]: It should begin with a number between 1 and 9

\d{0,2}: Followed by minimum 0, maximum 2 digits (0-9)

(?:,: Followed by a comma

\d{1,3})?: IF there is a comma it should be followed by one to three digits

$: End of line

EXAMPLE

Thanks @dev-null for this link: Explanation