Created
November 21, 2016 01:13
-
-
Save saltnpixels/7a44cb40c0749d049f7cdc4b4b92c9e1 to your computer and use it in GitHub Desktop.
gravity form minimum age validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
add_filter( 'gform_validation', 'profile_validation' ); | |
function profile_validation( $validation_result ) { | |
$form = $validation_result['form']; | |
//date of birth | |
$dob = rgpost('input_4'); //set to date field. also set below | |
// this the minimum age requirement we are validating | |
$minimum_age = 18; | |
//get difference in date and todays date | |
$from = new DateTime($dob); | |
$to = new DateTime('today'); | |
$age = $from->diff($to)->y; | |
// if age is smaller thna minimum age | |
if( $age < $minimum_age ){ | |
// set the form validation to false if age is less than minimum age | |
$validation_result['is_valid'] = false; | |
// find field with ID of 5 and mark it as failed validation | |
foreach($form['fields'] as &$field){ | |
//set to date field | |
if($field['id'] == '4'){ | |
$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; | |
} | |
} | |
} | |
$validation_result['form'] = $form; | |
return $validation_result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment