The Web Blinders logo

Programming

JavaScript regular expressions for matching wih Year-month (YYYY-MM) and Month/Year (MM/YYYY) patterns

HTML Inputs like Card expiry date require input in the format YYYY-MM,so you should know how to validate such input.
JavaScript - How to validate credit / debit card expiration date ?
Validating YYYY-MM and MM/YYYY patterns.

JavaScript for validating Year-Month ( YYYY-MM ) pattern


/*
Returns true if input matches correct YYYY-MM pattern
YYYY - starts with 1 or 2
MM - Valid 2 digit month less than or equal to 11
*/

function matchesYearAndMonth(input) {
    return /([12]\d{3}-(0[1-9]|1[0-2]))/.test(input);
}
console.log(matchesYearAndMonth('2012-01')); // true
console.log(matchesYearAndMonth('2012-12')); // true
console.log(matchesYearAndMonth('2012-13')); // false
console.log(matchesYearAndMonth('0000-01')); // false
console.log(matchesYearAndMonth('2000-1'));  // false

JavaScript - How to validate credit / debit card expiration date ?

Below code can be used to validate MM/YYYY Pattern


/*

Returns true if the input matches correct MM/YYYY pattern
MM - Valid 2 digit month less than or equal to 11
YYYY - starts with 1 or 2
*/

function matchesMonthAndYear(input) {
    return /((0[1-9]|1[0-2])\/[12]\d{3})/.test(input);
}
console.log(matchesMonthAndYear('10/2012')); // true
console.log(matchesMonthAndYear('02/2011')); // true
console.log(matchesMonthAndYear('13/2011')); // false
console.log(matchesMonthAndYear('1/0001'));  // false

You can use above codes for validating HTML YYYY-MM , MM/YYYY inputs or you can create custom pattern from above patterns.

Use comments section for any queries.

Need developers ?

if so, send a message.

thewebblinders@gmail.com

More Programming from our blog

SEARCH FOR ARTICLES