I have an input field that I need to check validity of the input.
The input needs to be 4 digits with the following masks:
08## and 09##, 4###, 5###, 6###, 7###
String examples:
"1234" // invalid
"abcd" // invalid
"5000" // valid
"0810" // valid
What is a regex that I can use to check the strings validity?
Something like:
regex.test('1234')
3
Answers
You could use the following regex pattern:
Sample script:
The regex used here says to match:
^
from the start of the string(?:
0[89]d{2}
starts with 08 or 09, followed by any 2 digits|
OR[4-7]d{3}
starts with 4, 5, 6, 7, followed by any 3 digits)
$
end of the stringyou can try this
You can use the following pattern.
Here is the Wikipedia article on regular expressions.
Wikipedia – Regular expression.
The syntax is very basic, despite appearing somewhat arcane.
You provide the static text you want to match, and when a character can range in value, you utilize the syntax—i.e.,
d
, or[4-7]
.It doesn’t take long to learn, the Wikipedia article covers it, entirely.
There are also some great books, O’Reilly Media has a few good ones.
O’Reilly Media – Mastering Regular Expressions.