Age Verification via Gravity Forms

For a recent site I needed a form which asked the user their birthdate and if they were under 13 years of age, tell them they weren’t able to register with the site. I use Gravity Forms for just about everything I do form-wise on the web, so of course I turned there first. With no shortage of help of their great support staff, I present to you this handy little code snippet to do just that.

Paste the following into your functions.php file, and be sure to change the gform_validation_420 and input_5 to accommodate your own form!. Oh, and again, this is for 13 years or older, change the $minimum_age from 13 to 18 or 21 or whatever you need.

// this code will run for form 420 only; change 420 to your form ID
add_filter('gform_validation_420', 'verify_minimum_age');
function verify_minimum_age($validation_result){

// retrieve the $form
$form = $validation_result['form'];

// date of birth is submitted in field 5 in the format YYYY-MM-DD
// change the 5 here to your field ID
$dob = rgpost('input_5');

// this the minimum age requirement we are validating
$minimum_age = 13;

// calculate age in years like a human, not a computer, based on the same birth date every year
$age = date('Y') - substr($dob, 0, 4);
if (strtotime(date('Y-m-d')) - strtotime(date('Y') . substr($dob, 4, 6)) < 0){ $age--; } // is $age less than the $minimum_age? if( $age < $minimum_age ){ // set the form validation to false if age is less than the minimum age $validation_result['is_valid'] = false; // find field with ID of 5 and mark it as failed validation foreach($form['fields'] as &$field){ // NOTE: replace 5 with the field you would like to mark invalid if($field['id'] == '5'){ $field['failed_validation'] = true; $field['validation_message'] = "Sorry, you must be at least $minimum_age years of age to join. You're $age years old."; break; } } } // assign modified $form object back to the validation result $validation_result['form'] = $form; return $validation_result; }

Up Next: How to Mark Topics as Read in BBPress Plugin for WordPress