Reputation: 51
I am trying to use regex to check if the user input is in the correct format xx-xx (input only accepts numbers, does not accept alphanumeric characters)
I tried: /[1-9]{1,}\-[1-9]{1,}/
but when entering alphabetic characters still pass this test.
Can you guys help me. Thank.
Upvotes: 3
Views: 137
Reputation: 160
On the other hand, you can have several cases depending on what you are looking for precisely.
In case you agree that an xx-xx value can be 00-00 and any other value, you should use this regex instead:
/^\d{2}-\d{2}$/
In case you accept that an xx-xx value is never 00-00 but can be 01-03 and any other value, but never 00-00, you should use this regex (a bit long, sorry, but does the job perfectly):
/^[1-9](?=[0-9])[0-9]-[1-9](?=[0-9])[0-9]$|^[0-9](?=[1-9])[1-9]-[0-9](?=[1-9])[1-9]$/
Enjoy !
Upvotes: 0
Reputation: 160
Your regex is just fine, you just need to add positional asserts, "^" for the start of the string and "$" for the end of the string:
/^[1-9]{2}\-[1-9]{2}$/
It is better to put "{2}" if you only want xx-xx
Upvotes: 2
Reputation: 126
/\d{2}-\d{2}/
Worked for me.
Breakdown:
\d checks for a digit character, i.e. 0-9.
{2} checks for two digits next to each other specifically.
- just checks for the hyphen character.
Upvotes: 0