SHARE
TWEET

Validate minimum age in a date field

chrishajer Jan 16th, 2013 487 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // http://www.gravityhelp.com/forums/topic/check-date-greater-than-18-yrs#post-122525
  2. // http://www.gravityhelp.com/documentation/page/Gform_validation
  3. // this code will run for form 274 only; change 274 to your form ID
  4. add_filter('gform_validation_274', 'verify_minimum_age');
  5. function verify_minimum_age($validation_result){
  6.  
  7.     // retrieve the $form
  8.     $form = $validation_result['form'];
  9.  
  10.         // date of birth is submitted in field 5 in the format YYYY-MM-DD
  11.         // change the 5 here to your field ID
  12.         $dob = rgpost('input_5');
  13.  
  14.         // this the minimum age requirement we are validating
  15.         $minimum_age = 13;
  16.  
  17.         // calculate age in years like a human, not a computer, based on the same birth date every year
  18.         $age = date('Y') - substr($dob, 0, 4);
  19.         if (strtotime(date('Y-m-d')) - strtotime(date('Y') . substr($dob, 4, 6)) < 0){
  20.             $age--;
  21.         }
  22.  
  23.     // is $age less than the $minimum_age?
  24.     if( $age < $minimum_age ){
  25.  
  26.         // set the form validation to false if age is less than the minimum age
  27.         $validation_result['is_valid'] = false;
  28.  
  29.         // find field with ID of 5 and mark it as failed validation
  30.         foreach($form['fields'] as &$field){
  31.  
  32.             // NOTE: replace 5 with the field you would like to mark invalid
  33.             if($field['id'] == '5'){
  34.                 $field['failed_validation'] = true;
  35.                 $field['validation_message'] = "Sorry, you must be at least $minimum_age years of age to join. You're $age years old.";
  36.                 break;
  37.             }
  38.  
  39.         }
  40.  
  41.     }
  42.     // assign modified $form object back to the validation result
  43.     $validation_result['form'] = $form;
  44.     return $validation_result;
  45. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top