'Gravity Forms Wordpress Date Picker Age Verification
I am using Gravity Forms (1.8.9) and Wordpress (3.9.1)
I have a form field as a datepicker on my site, and I want to allow submissions only if the user is 21 or older to be able to submit the form.
I was originally using the following code. It only worked for a single form for a while, but then it stopped working completely: http://lanche86.com/gravity-forms-18-years-old-verification/
I would like to be able to use the same code on different forms. Help!
Solution 1:[1]
You can do something like this:
add_filter("gform_field_validation_1_1", "dob_validate", 10, 4);
function dob_validate($result, $value, $form, $field){
//Check if dob field matches required age
if ($result["is_valid"]){
// this the minimum age requirement we are validating
$minimum_age = 18;
// calculate age in years like a human, not a computer, based on the same birth date every year
$age = date('Y') - substr($value, 6, 4);
if (strtotime(date('Y-m-d')) - strtotime(date('Y') . '-' . substr($value, 0, 2) . '-' . substr($value, 3, 2)) < 0) {
$age--;
}
if( $age < $minimum_age ){
$result["is_valid"] = false;
$result["message"] = "Sorry, you must be at least $minimum_age years old. You're $age years old.";
}
}
//Check if dob field is empty
if(empty($value)){
$result["is_valid"] = false;
$result["message"] = "This field is required.";
}
return $result;
}
I'm using Gravity Forms 1.8.8 and latest Wordpress and works as desired. Screenshot:

You can also edit this according to form and field:
add_filter("gform_field_validation_1_1", "dob_validate", 10, 4);
Where gform_field_validation_1_1 is for form 1 and field 1. If your forms id is 8 and field number is 2, you can change it to gform_field_validation_8_2.
You can also add that same filter multiple times for multiple forms and fields without recreating the dob_validate function.
Solution 2:[2]
If anybody still needs to implement this, try this:
add_filter( 'gform_field_validation_1_1', function ( $result, $value, $form, $field ) {
if ( $result['is_valid'] ) {
if ( is_array( $value ) ) {
$value = array_values( $value );
}
$date_value = GFFormsModel::prepare_date( $field->dateFormat, $value );
$today = new DateTime();
$diff = $today->diff( new DateTime( $date_value ) );
$age = $diff->y;
if ( $age < 18 ) {
$result['is_valid'] = false;
$result['message'] = 'Underage';
}
}
return $result;
}, 10, 4 );
It's on Gravity Forms Documentation: https://docs.gravityforms.com/gform_field_validation/#13-date-field-age-validation
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | designtocode |
| Solution 2 | Trending Consullting |
