Minimum Age Check on a Gravity Forms Date of Birth
Rejects a Gravity Forms date of birth that makes the person younger than the age you set, for age-restricted sign-ups and applications.
Opens WPIDE on
Code
$wpide_gf_min_age = 18;
add_filter( 'gform_field_validation', function ( $result, $value, $form, $field ) use ( $wpide_gf_min_age ) {
if ( 'date' !== $field->type || ! $result['is_valid'] || false === strpos( ' ' . $field->cssClass . ' ', ' date-of-birth ' ) ) {
return $result;
}
if ( is_array( $value ) ) {
$value = implode( '/', array_values( $value ) );
}
$format = ! empty( $field->dateFormat ) ? $field->dateFormat : 'mdy';
$parts = preg_split( '/[\/\-.]/', (string) $value );
if ( 3 !== count( $parts ) ) {
return $result;
}
$map = array( 'mdy' => array( 2, 0, 1 ), 'dmy' => array( 2, 1, 0 ), 'dmy_dash' => array( 2, 1, 0 ), 'dmy_dot' => array( 2, 1, 0 ), 'ymd_slash' => array( 0, 1, 2 ), 'ymd_dash' => array( 0, 1, 2 ), 'ymd_dot' => array( 0, 1, 2 ) );
$idx = isset( $map[ $format ] ) ? $map[ $format ] : $map['mdy'];
$birth = sprintf( '%04d-%02d-%02d', (int) $parts[ $idx[0] ], (int) $parts[ $idx[1] ], (int) $parts[ $idx[2] ] );
$limit = wp_date( 'Y-m-d', strtotime( '-' . $wpide_gf_min_age . ' years' ) );
if ( $birth > $limit ) {
$result['is_valid'] = false;
$result['message'] = sprintf( 'You must be at least %d years old.', $wpide_gf_min_age );
}
return $result;
}, 10, 4 );
Notes
Add the CSS class date-of-birth to the date field; works with every Gravity Forms date format.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.