Home > Net >  Regular expression for format xx-xx (does not contain letters)
Regular expression for format xx-xx (does not contain letters)

Time:08-05

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.

CodePudding user response:

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

CodePudding user response:

/\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.

  • Related