Home > Back-end >  match date in format mm/dd/yyyy
match date in format mm/dd/yyyy

Time:08-17

I need a regex that would match date in mm/dd/yyyy. I have a following Javascript regex /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/

it matched 12/31/2022 or 01/09/2022 but not 1/9/2022. I was not able to create regex that would satisfy it. Is there any way to implement this ?

CodePudding user response:

You can make leading 0 optional by adding 0?:

/^(0?[1-9]|1[0-2])\/(0?[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/

CodePudding user response:

ONLY use regex to parse the datestring, then create a date object and test it matches the input.

I made a function that can test either US or EU dates

const re = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/; 
const validDate = (str,eur) => { // US date is default
  if (typeof str !== "string" || str.trim() === "" || !re.test(str)) return false
  let [_,mm,dd,yyyy] = str.match(re); // spread
  if (eur) [mm, dd] = [dd, mm];
  const d = new Date(yyyy,mm-1,dd,15,0,0,0); // normalise away from midnight
//      console.log(dd,mm,yyyy,d.toLocaleDateString());
  return d.getFullYear() ===  yyyy && d.getMonth() === (mm-1) && d.getDate() ===  dd;
};

["12/31/2022",
"01/09/2022",
"1/9/2022",
"02/29/2021", // not a leap year
"02/29/2020", // a leap year
"99/99/9999",
12312022,
""].forEach(str => console.log(str,validDate(str)));
console.log("-------- Europeean --------");
// European DD/MM/YYYY
["31/12/2022",
"09/01/2022",
"9/1/2022",
"29/2/2021", // not a leap year
"29/02/2020", // a leap year
"99/99/9999",
12312022,
""].forEach(str => console.log(str,validDate(str,true)))

  • Related