Anna
Anna

Reputation: 23

Using Regular Expression to Format Date

I am trying to ensure the date is in YYYY-MM-DD with the following code:

var exp = \d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01]);

for(i=0; i<array.length; i++)
    if(!exp.test(array[i].value)
        //do something 

What i have is currently not working, the contents of my if statement are not executing, which leads me to believe either my if statement is set up wrong or my regular expression is wrong, I am stuck on it and cannot figure it out

Upvotes: 1

Views: 50

Answers (4)

mplungjan
mplungjan

Reputation: 178421

Your regex will allow invalid dates. Here is how to test

const isDate = dString => {
  const [yyyy, mm, dd] = dString.split("-");
  let d = new Date(yyyy, mm - 1, dd, 15, 0, 0, 0); // handling DST
  return d.getFullYear() === +yyyy &&   // casting to number
         d.getMonth()    === mm - 1 &&
         d.getDate()     === +dd;
}
const arr = ["2019-01-01", "2019-02-29"]

arr.forEach(dString => console.log(isDate(dString)))

Upvotes: 1

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92743

I don't check your regexp, but you should put it between / and / - however for date validation regexp are not good tool - e.g. case 2019-02-29 is invalid... But you can use it for initial format checking e.g.

let dateString = "2019-05-14";

let [d,year,month,day]= dateString.match(/(\d{4})-(\d{2})-(\d{2})/)||[]

if(d) {
  // here make deeper validation
  console.log({year,month,day})
} else {
  console.log('invalid');
}

Upvotes: 0

Nicolas
Nicolas

Reputation: 8695

You are not declaring your regex correctly. you need to use /regex/. Also, you are testing if your string doesn't match, you might want to make sure that's what you really want.

var exp = /\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01])/;
let dateString = "2019-05-40";

if(!exp.test(dateString)) {
   console.log('not matching');
}

Upvotes: 0

ArunPratap
ArunPratap

Reputation: 5020

as you mentioned you want date format yyyy-mm-dd you can use bellow regex

/([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/

var exp = /([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/;
let yourDate= "2018-09-26";

if(exp.test(yourDate)) {
   console.log('Date Formated!');
}

Upvotes: 0

Related Questions