A simple way to determine whether the input string is in date format

  • 2021-07-02 23:27:04
  • OfStack

The example is as follows:


function isDate(dateString){
  if(dateString.trim()=="")return true;
  var r=dateString.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/); 
  if(r==null){
   alert(" Please enter a properly formatted date \n\r Date format: yyyy-mm-dd\n\r Example    Such as: 2008-08-08\n\r");
  return false;
  }
  var d=new Date(r[1],r[3]-1,r[4]);  
  var num = (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]);
  if(num==0){
   alert(" Please enter a properly formatted date \n\r Date format: yyyy-mm-dd\n\r Example    Such as: 2008-08-08\n\r");
  }
  return (num!=0);
 } 

Related articles: