I want to make user to enter numbers in 0-20 range and they can both enter 01 and 1
this is what I have so far
/^[1-9]|0[1-9]|1[0-9]|2[0]$/
but it doesn't work.
With regex you have a couple of options to match a digit. You can use a number from 0 to 9 to match a single choice. Or you can match a range of digits with a character group e.g. [4-9]. If the character group allows any digit (i.e. [0-9]), it can be replaced with a shorthand (\d).
To check for all numbers in a field To get a string contains only numbers (0-9) we use a regular expression (/^[0-9]+$/) which allows only numbers. Next, the match() method of the string object is used to match the said regular expression against the input value.
Go to the question's Settings. Go to Validation Criteria and choose the Manually enter your validation logic in XLSForm code option. In the Validation Code box, enter your regex formula between the quotation marks (' ') of the regex(., ' ') format.
$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.
The problem is that |
has lower precedence than ^
and $
, so your pattern means ^[1-9]
or 0[1-9]
or 1[0-9]
or 2[0]$
: only single-digit values are restricted by ^
, and only 20
is restricted by $
.
You can either repeat ^
and $
in each branch of the alternation, or else wrap the alternation in (?:...)
to create a non-capturing subexpression:
/^[1-9]$|^0[1-9]$|^1[0-9]$|^20$/
/^(?:[1-9]|0[1-9]|1[0-9]|20)$/
(I've also taken the liberty of changing [0]
to 0
.)
try this
/^([01]?\d|20)$/
0 or 1 (optional) followed by at least one digit OR 20
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With