Friday, January 29, 2010

Date and Time validation using Regular Expression

This function is used for date validation on a string
Return of this function is boolean.
function is_date($str){
   $return = (bool) preg_match("(\b([1-9]([0-9]{3}))\-(1[0-2]|0[1-9])\-(3[01]|[12][0-9]|0[1-9])\b)",$str);
   if(strlen($str)==10){
      return $this->is_date_time($str);
   }
   if($return){
     $return = (bool) (strlen($str)==10);
   }
   return $return;
}


This function is used for time validation on a string
Return of this function is boolean.
function is_time($str){
   $return = (bool) preg_match("(\b(2[0-3]|[01][0-9])\:([0-5][0-9])\:([0-5][0-9])\b)",$str);
   if($return){
      $return = (bool) (strlen($str)==8);
   }
   return $return;
}



And This function is used for date_time validation on a string
Return of this function is boolean.
function is_date_time($str){
   $return = (bool) preg_match("(\b([1-9]([0-9]{3}))\-(1[0-2]|0[1-9])\-(3[01]|[12][0-9]|0[1-9]) (2[0-3]|[01][0-9])\:([0-5][0-9])\:([0-5][0-9])\b)",$str);
   if($return){
      $return = (bool) (strlen($str)==19);
   }
   return $return;
}

No comments:

Post a Comment