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.
Solution 1:
[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
^
- start of string(?:[0-9]{1,3}(?:,[0-9]{3})*)?
- an optional sequence of[0-9]{1,3}
- one to three digits(?:,[0-9]{3})*
- 0 or more repetitions of,
- comma[0-9]{3}
- three digits
\.
- dot[0-9]{2}
- two digits$
- end of string.
Post a Comment for "Can't Get Regex Pattern To Work Correctly In Mvc 5 View Using Javascript"