Search code examples
javascriptregexvalidation

Regular Expression Regex for Format MMYY for current year (e.g) 19 and future years in javascript


I need a regular expression to be used in credit card form the rule is simple, the format must be MMYY.

I could achieve that with this regular expression.

/^(0[1-9]|1[0-2])\d{2}$/

Now am researching to apply validation to make YY 19 for the current year and in future years.

Maybe its hard to make it dynamic, but i can replace the string 19 from current year in javascript, so now I just want it fixed for 19 and above.

Example of valid MMYY:

0126

1220

0119

Example of In Valid MMYY

0101

1111

1218

Here is reference of what i have now Example shared for my reg exp looks like


Solution

  • Given a year for which that year and future years should pass, it'd be a bit tedious to dynamically construct such a regular expression. Consider using a capture group instead, and then just check whether the captured YY is greater than or equal to the limit:

    const yearLimit = 19; // or pass this as an argument if you want
    
    const re = /^(?:0[1-9]|1[0-2])(\d{2})$/;
    const match = str.match(re);
    if (!match) {
      return false;
    }
    const year = Number(match[1]);
    return year >= yearLimit;
    

    const validate = (str) => {
      const yearLimit = 19; // or pass this as an argument if you want
    
      const re = /^(?:0[1-9]|1[0-2])(\d{2})$/;
      const match = str.match(re);
      if (!match) {
        return false;
      }
      const year = Number(match[1]);
      return year >= yearLimit;
    };
    
    console.log(
      validate('1234'),
      validate('1212')
    );

    ^(?:0[1-9]|1[0-2])(\d{2})$ means

    • ^ - Match start of string
    • (?:0[1-9]|1[0-2]) - Match 01-12: either
      • 0[1-9] - Leading 0, followed by a number 1 to 9, or
      • 1[0-2] - Leading 1, followed by a number 0 to 2
    • (\d{2}) - Match and capture any two digits
    • $ - Match end of string