Validating 18 with Date field

I am using this code from https://docs.gravityforms.com/gform_field_validation/ to validate the age of a user registering, which works.
Instead of stopping the flow of the registration with “Underage”, I want to Enable Conditional Logic to show a parental consent option if the user is a minor.
How do I accomplish this?

//Validate 18
add_filter( 'gform_field_validation_10_2' , 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 );

Because you want to use the age in conditional logic, the gform_field_validation filter is not the right choice. I recommend using this to calculate the number of days between two dates:

That will calculate the number of days between two date fields. You will probably be asking them one date (the birthdate.) You don’t really want to ask them today’s date. So you can use this approach to dynamically populate a field with today’s date:

Now, you have two date fields, and you can configure the Gravity Wiz snippet to calculate the number of days between the two dates, If you use the value of 18 years * 365 days in your conditional logic (something like IF AGE is LESS THAN 6570 SHOW the consent field.)

That’s not a perfect solution, because you really need to know if the birth date was at least 18 years prior to May 30, 2002 (not number of days.) In any event, the gform_field_validation filter would not be the right one to use. You will need to do something live in the form to calculate the age, populate a field with that age, and then use that age value in your conditional logic rule.

EDIT: if you were using a multi-page form, you could use gform_field_validation after the birthdate is submitted, figure out the age in years, and then populate a field in the form that is used on the next page in your conditional logic rules.

© 2008 - 2019. Gravity Forms is a project by Rocketgenius Inc.