Tuesday, October 1, 2013

Adding custom form validation to Contact Form 7 in Wordpress

I needed to add custom validation to a Contact Form 7 form on a Wordpress site to check if an email was already recorded in our database.

I found a great example of how to do something similar here:
http://wordpress.org/support/topic/plugin-contact-form-7-custom-field-validation-code

I made my own even simpler example to save for future reference. In this example I check if the provided email ends in @gmail.com. If it does not, we provide an error message.

You need to put the code in the theme's functions.php file:

 function is_gmail($email) {  
      if(substr($email, -10) == '@gmail.com') {  
           return true;  
      } else {  
           return false;  
      };  
 };  
 function custom_email_validation_filter($result, $tag) {  
      $type = $tag['type'];  
      $name = $tag['name'];  
      if($name == 'your-email') { // Only apply to fields with the form field name of "your-email"  
           $the_value = $_POST[$name];  
           if(!is_gmail($the_value)){  
                $result['valid'] = false;  
                $result['reason'][$name] = 'This is not a gmail address!'; // Error message  
           };  
      };  
       return $result;  
 };  
 add_filter('wpcf7_validate_email','custom_email_validation_filter', 10, 2); // Email field  
 add_filter('wpcf7_validate_email*', 'custom_email_validation_filter', 10, 2); // Required Email field