skip to Main Content

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


  1. You could use the following regex pattern:

    ^(?:0[89]d{2}|[4-7]d{3})$
    

    Sample script:

    var input = ["1234", "abcd", "5000", "0810"];
    
    input.forEach(x => console.log(x + " => " + /^(?:0[89]d{2}|[4-7]d{3})$/.test(x)));

    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 string
    Login or Signup to reply.
  2. you can try this

    const regex = /^(08d{2}|09d{2}|[4-7]d{3})$/;
    console.log(regex.test('1234')); 
    console.log(regex.test('abcd'));
    console.log(regex.test('ABCD'));
    console.log(regex.test('ABcD'));
    console.log(regex.test('5000'));
    console.log(regex.test('0810')); 
    • ^ start of the string.
    • 08d{2}, 09d{2} matches "08" and "09" followed by any two digits
    • [4-7]d{3} matches a digit from 4 to 7 followed by any three digits.
    • $ end of the string.
    Login or Signup to reply.
  3. You can use the following pattern.

    0[89]dd|[4-7]d{3}
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search