Reputation: 11995
I have a regex to validate the amount entered in a field: /^\d+(\.\d+)?$/
Can I somehow compound the expression such that I can check for the total no.of characters entered? It should allow for a max of 13 characters (with/without decimal)
Upvotes: 3
Views: 90
Reputation: 93046
To define a maximum length you can use a positive lookahead
/^(?=.{0,13}$)\d+(\.\d+)?$/
(?=.{0,13}$)
is a look ahead assertion, meaning are there between 0 and 13 characters ahead till the end of the string?
You can also do this separately for the part before and after the dot like this
^(?=[^.]{1,5}(?:\.|$))\d+(?:\.(?=.{1,4}$)\d+)?$
See it here online on Regexr
The first look ahead checks for NOT a dot ([^.]
) 1 to 5 times, till it finds a dot or the end of the string. The second look ahead checks for 1 to 4 characters after the dot till the end of the string.
Upvotes: 1
Reputation: 336478
Sure, just add a lookahead assertion at the start:
/^(?=.{0,13}$)\d+(\.\d+)?$/
^(?=.{0,13}$)
makes sure that there are between 0 and 13 characters between start and end of string. It doesn't actually match and consume any of those characters, so the following part of the regex can then do the validation.
Another way would be
/^(?!.{14})\d+(\.\d+)?$/
Here, (?!.{14})
asserts that it's impossible to match 14 characters at the start of the string, thereby ensuring a length maximum of 13.
Other variations on this theme:
/^(?=.{13})\d+(\.\d+)?$/ # more than 12 characters
/^(?=.{6}$|.{8}$)\d+(\.\d+)?$/ # 6 or 8 characters
Upvotes: 3