简体   繁体   中英

Regular expression for date validation

I am having a problem in validating the date, In my code I have used a regular expression which accepts dates of year 2012, if I give date having yr as 2013 it says "Invalid date". Kindly help me on this regard. It should accept any years.. I mean valid years atleast from year 2000 to year 3000. Thanks in advance.

function checkDates(){
  var sdate = "2013-01-02";
  var edate = "2013-01-02";

  if (!isValidDate(sdate)) {
         alert("Report Start Date is Invalid!!");
         return false;
    } 

    if (!isValidDate(edate)) {
     alert("Report End Date is Invalid!!");
     return false;
   }
   return true;
}


function isValidDate(sText) {

    var reDate = /(?:([0-9]{4}) [ -](0[1-9]|[12][0-9]|3[01])[ -]0[1-9]|1[012])/;  // yy/mm/dd
    return reDate.test(sText);
}

There's an extra space in your regex and missing brackets (bracket issue makes it accept 2012-aa-xx date:

/(?:([0-9]{4}) [ -](0[1-9]|[12][0-9]|3[01])[ -]0[1-9]|1[012])/
              ^                               ^
-------------/-------------------------------/

So:

([0-9]{4}[ -](0[1-9]|[12][0-9]|3[01])[ -](0[1-9]|1[012]))

the below expression also works

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

Thanks, Dhiraj

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