Allow Only Future Dates in Gravity Forms Date Fields
Rejects dates in the past in Gravity Forms date fields used for bookings, deliveries or appointments, with an optional number of days' notice.
Opens WPIDE on
Code
$wpide_gf_notice_days = 1; // Days of notice required; 0 allows today.
add_filter( 'gform_field_validation', function ( $result, $value, $form, $field ) use ( $wpide_gf_notice_days ) {
if ( 'date' !== $field->type || ! $result['is_valid'] || false === strpos( ' ' . $field->cssClass . ' ', ' future-date ' ) || empty( $value ) ) {
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'];
$date = sprintf( '%04d-%02d-%02d', (int) $parts[ $idx[0] ], (int) $parts[ $idx[1] ], (int) $parts[ $idx[2] ] );
if ( $date < wp_date( 'Y-m-d', time() + $wpide_gf_notice_days * DAY_IN_SECONDS ) ) {
$result['is_valid'] = false;
$result['message'] = $wpide_gf_notice_days ? sprintf( 'Please choose a date at least %d day(s) from today.', $wpide_gf_notice_days ) : 'Please choose today or a later date.';
}
return $result;
}, 10, 4 );
Notes
Add the CSS class future-date to a date field; set the minimum notice in days at the top (0 allows today).
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.