Thursday, August 2, 2012

Contact form 7 custom validation

While building a  wordpress theme for one of my client I came across some validation issues for contact form7 where two data must show logical error when check in date is bigger than the check out date. First, thing came into my mind is to edit the plugin itself, but this is not the proper solution because if client updates the plugin then my codes will broken again.

Another, solution was to use contact form 7's hooks. The filter 'wpcf7_validate_text' provides a way to directly send validation errors when your requirement is not fulfilled.



 So, here is my code.
 
<?php
// CF7 Custom Validation Rules

/*
Compare date function
*/
function compare_date($date1, $date2) {
  $date1 = explode('/', $date1);
  $date2 = explode('/', $date2);
  
  $output = false;
  
  if($date2[2] > $date1[2]) {
  $output = true;
  } else {
  $output = false;
  }
  
  if($date2[2] == $date1[2]) {
  if($date2[0] > $date1[0]) {
  $output = true;
  } else {
  $output = false;
  }
  
  if($date2[0] == $date1[0]) {
  if($date2[1] >= $date1[1]) {
  $output = true;
  } else {
  $output = false;
  }
  }
  }

 if ($output) {
  return true;
  } else { 
  return false;
  }

}

/*
Function called via wpcf7_validate_text filter
*/
function cf7_custom_form_validation($result,$tag) {
  $type = $tag['type'];
  $name = $tag['name'];
  $CheckInDate = $_POST['CheckInDate'];
  $CheckOutDate = $_POST['CheckOutDate'];
  
  if($name == 'CheckInDate'){
  if(!compare_date($CheckInDate, $CheckOutDate)) {
  $result['valid'] = false;
  $result['reason'][$name] = 'Logical Error: Check in date should be before check out date';
  }
  }
  
  if($name == 'CheckOutDate'){
  if(!compare_date($CheckInDate, $CheckOutDate)) {
  $result['valid'] = false;
  $result['reason'][$name] = 'Logical Error: Check out date should be After check in date';
  }
  }
 return $result;
  }

/*
add filter wpcf7_validate_text to call the custom validation function
*/
add_filter('wpcf7_validate_text','cf7_custom_form_validation', 10, 2); // Email field

/*
Filter for required field
*/
  add_filter('wpcf7_validate_text*', 'cf7_custom_form_validation', 10, 2); // Req. Email field

?>


Just save this code in a new file and include the file using php include function inside your functions.php. When you try submitting the form, it will show your custom validation errors if the requirement is not fulfilled.

No comments:

Post a Comment