const regex = /^((\d{2}(?!0229))|([02468][048]|[13579][26])(?=0229))(0[1-9]|1[0-2])(0[1-9]|[12]\d|(?<!02)30|(?<!02|4|6|9|11)31)\-(\d{2})\-(\d{4})$/gm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('^((\\d{2}(?!0229))|([02468][048]|[13579][26])(?=0229))(0[1-9]|1[0-2])(0[1-9]|[12]\\d|(?<!02)30|(?<!02|4|6|9|11)31)\\-(\\d{2})\\-(\\d{4})$', 'gm')
const str = `Case 1:
Correct
Month with 31days
000131-01-1728
Month with 30days
000430-01-1728
Feb with 28days
010228-01-1728
Feb with 29days
200229-01-1728
Feb with 29days
960229-01-1728
Case 2:
Invalid
Invalid date 32nd
990132-01-1728
Invalid date 31st for april
000431-01-1728
Invalid date 29th for feb in non leap year
010229-01-1728
Invalid date 30th for feb in leap year
200230-01-1728
Invalid month 13th
201301-01-1728
Invalid month 00th
200001-01-1728
Invalid date 00th
200100-01-1728`;
// Reset `lastIndex` if this regex is defined globally
// regex.lastIndex = 0;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions