Last active
September 12, 2018 21:43
-
-
Save wearehyphen/42483f2a9b8cf7c7d072 to your computer and use it in GitHub Desktop.
Gravity Forms: Validate Arrival & Departure Dates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*** | |
* Gravity Forms: Validate to ensure date fields are not the same or todays date | |
* | |
* This will validate the fields on form submission and return a validation error on the fields in question. | |
* In this case it validates an Arrival and Departure date against each other and today's date. | |
* | |
* Code goes in your theme's functions.php file. | |
***/ | |
add_filter('gform_field_validation','validate_dates',10,4); | |
function validate_dates($result,$value,$form,$field){ | |
// Set ut variables for use | |
$today = time(); // Use UNIX timestamp for comparison | |
$arrivalDate = ''; | |
$departureDate = ''; | |
// Arrival Date-field. Replace '4' with your field ID | |
if($field['id'] === 4) { | |
$date = DateTime::createFromFormat('d/m/Y',$value); // Create DateTime based on the value of the field. Replace 'd/m/Y' with the value of your Date-field | |
$arrivalDate = intval($date->format('U')); // Get UNIX timestamp based on $date | |
// Check if $arrivalDate is before or on today's date, if true; fail validation. | |
if($arrivalDate <= $today) { | |
$result['is_valid'] = false; // Fail validation | |
$result['message'] = "Arrival date can't be on or before today's date."; // Your message here | |
} | |
} | |
// Departure Date-field. Replace '7' with your field ID | |
if($field['id'] === 7 && $value) { | |
$date = DateTime::createFromFormat('d/m/Y',$value); | |
$departureDate = intval($date->format('U')); | |
// Check if $departureDate is before or on $arrivalDate OR before or on today's date, if either is true; fail validation. | |
if($departureDate <= $arrivalDate || $departureDate <= $today) { | |
$result['is_valid'] = false; // Fail validation | |
$result['message'] = "Departure date can't be on or before arrival or today's date."; // Your message here | |
} | |
} | |
return $result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment