javascriptregexasp.net-mvc-5asp.net-mvc-views

Can't get RegEx pattern to work correctly in MVC 5 View using Javascript


Here is my pattern. I'm trying to allow numbers and a decimal with two places plus an optional comma with three digits.

var pattern = /^[0-9]+(,\d{3})*\.[0-9]{2}$/;

Allow

100,000.12

10,000.12

1,000.12

100.12

10.12

.12 (can't get this to allow... see below)

Don't allow

abcd

1,,000.12

1,00.12

1,000.0

1,000.

1,000

Here is the test. If I add a ? after [0-9] it works here, but it does not work in my MVC 5 View. The modal doesn't open, so MVC doesn't like it.

^[0-9]?+(,\d{3})*\.[0-9]{2}$

https://regex101.com/r/HwLS7q/1

UPDATE 1

Don't allow

000,000.12, 0.12 etc...

Any help is much appreciated! Thanks!


Solution

  • [0-9]?+ is a pattern that matches 1 or 0 digits possessively, not allowing backtracking into the pattern. JS regex does not support possessive quantifiers, hence the issue.

    You need to use

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

    Or

    ^(?:[0-9]+(?:,[0-9]{3})*)?\.[0-9]{2}$
    

    Here, the [0-9]* match zero or more digits and (?:[0-9]+(?:,[0-9]{3})*)? matches an optional sequence of 1+ digits followed with 0+ repetitions of , and 3 digit groups.

    See this regex demo.

    A more precise pattern would be to restrict the first digit chunk to 1, 2 or 3 digits and make the integer part optional:

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

    See the regex demo.

    Details