Age validation specific date [RESOLVED]

Hi all,

We just started with Gravity Forms and I love how the community is interacting and writing solutions as an extension of the well-written docs.

Now, we’ve just implemented a form with the age validation check written in this document: https://docs.gravityforms.com/gform_field_validation/#h-13-date-field-age-validation. As the user signs up for an event on a specific date, I am wondering if the age validation can be edited to ‘the event date’.

E.g. the event is on the 03 of September 2023 and the attendee must be 18 on the event date, when signing up for this event he isn’t 18 yet, but on the event date, this person is. How can we manage to check the age based on the age validation hook?

Sincerely,
Matthijs

Hi, Matthijs!

There is just one line you need to change to do what you want. In the line that has new DateTime(), you can just insert the date you want. So in your case, you would change the code snippet to this:

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( '2023-11-03` );
        $diff  = $today->diff( new DateTime( $date_value ) );
        $age   = $diff->y;
  
        if ( $age < 18 ) {
            $result['is_valid'] = false;
            $result['message']  = 'Underage';
        }
    }
  
    return $result;
}, 10, 4 );

Let me know if that doesn’t do what you need!

1 Like

Thank you so much for the explanation. I forgot quotes the other day, that explains why I got an error loading the whole website.

Thanks again!

2 Likes