Regular Expressions 101

Community Patterns

Your search did not match anything

Community Library Entry

1

Regular Expression
PCRE2 (PHP >=7.3)

/
^((([1-9])|([0][1-9])|([1-2]\d)|([3][01]))\.(([1-9])|([0][1-9])|([1][012]))\.\d{4})$
/
gm

Description

Initial date format: DD.MM.YYYY. Use additional user code to check if new Date(year, month, day) equal to initial input day.month.year

Script (typescript):

public static IsDateValid(date: string) {
  // check format DD.MM.YYYY, example good input, but invalid date '29.04.2025'
  if (!/^((([1-9])|([0][1-9])|([1-2]\d)|([3][01]))\.(([1-9])|([0][1-9])|([1][012]))\.\d{4})$/.test(date)) {
    return false;
  }

  let digits = date.split('.');

  // just to make sure if first step failed (can be removed)
  if (digits.length !== 3) {
    return false;
  }

  let year: number = Number.parseInt(digits[2]);
  let monthIdx: number = Number.parseInt(digits[1]) - 1;
  let day: number = Number.parseInt(digits[0]);

  // new Date will give '01.05.2025', instead of '29.04.2025'
  let testDate = new Date(year, monthIdx, day);
  if (!(testDate.getFullYear() === year && testDate.getMonth() === monthIdx && testDate.getDate() === 
day)) {
    console.log(`${testDate.getFullYear()}=${year} && ${testDate.getMonth()}=${monthIdx} && ${testDate.getDate()}=${day}`);
    return false;
  }

  return true;
}
Submitted by anonymous - 2 months ago (Last modified 2 months ago)