So I am completely not knowing in where to start in creating a RegEx validation pattern in my React application.
I have various input boxes, of which (depending on c
As in my comment below your question, you can use the following regex:
See regex in use here
^(?!9+[98]$|\d1{2})\d{3,6}$
How it works:
^
assert position at the start of the line(?!9+[98]$|\d1{2})
negative lookahead ensuring either of the the following options does not proceed
9+[98]$
matches 9
one or more times, then either 9
or 8
, then the end of the line\d1{2})
matches any digit, followed by 1
twice\d{3,6}
matches between 3 and 6 digits$
assert position at the end of the lineSince the negative lookahead follows the start of line anchor, we also ensure the lookahead starts at that position, that's why \d1{2}
matches 011
, 111
, 211
, ..., 911
and not 1211
or others.
Code below:
s = ['999','998','911','611','9999','9998','8112','5112','99999','99998','71122','41122','999999','999998','611222','311222','123','6211','99989','121212']
r = /^(?!9+[98]$|\d1{2})\d{3,6}$/
for (x of s) {
console.log(x.match(r) ? x + ': true' : x + ': false')
}
--
The OP mentioned that 999
and 998
placed anywhere in the string should invalidate it:
See regex in use here
^(?!\d*9{2}[98]|\d1{2})\d{3,6}$
Same regex as above except for the first option in the negative lookahead. It's now \d*9{2}[98]
, matching 999
or 998
anywhere in the string (preceded by any number of digits).
s = ['999','998','911','611','9999','9998','8112','5112','99999','99998','71122','41122','999999','999998','611222','311222','123','6211','99989','121212']
r = /^(?!\d*9{2}[98]|\d1{2})\d{3,6}$/
for (x of s) {
console.log(x.match(r) ? x + ': true' : x + ': false')
}
--
The OP mentioned that the format of 0N11
should be invalidated (not just N11
):
See regex in use here
^(?!\d*9{2}[98]|[01]?\d1{2})\d{3,6}$
Same regex as above except for the second option in the negative lookahead. It's now [01]?\d1{2}
, matching 0
or 1
optionally, followed by any digit, then 11
(so 011
, 111
, 211
, ..., 911
, 0011
, 0111
, 0211
, 0311
, ..., 0911
, 1011
, 1111
, 1211
, ..., 1911
).
s = ['999','998','911','611','9999','9998','8112','5112','99999','99998','71122','41122','999999','999998','611222','311222','123','6211','99989','121212']
r = /^(?!\d*9{2}[98]|[01]?\d1{2})\d{3,6}$/
for (x of s) {
console.log(x.match(r) ? x + ': true' : x + ': false')
}