简体   繁体   中英

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

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)))

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

 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'); }

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'); }

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!'); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM