You can do something like this:
add_filter("gform_field_validation_1_1", "dob_validate", 10, 4);
function dob_validate($result, $value, $form, $field){
//Check if dob field matches required age
if ($result["is_valid"]){
// this the minimum age requirement we are validating
$minimum_age = 18;
// calculate age in years like a human, not a computer, based on the same birth date every year
$age = date('Y') - substr($value, 6, 4);
if (strtotime(date('Y-m-d')) - strtotime(date('Y') . '-' . substr($value, 0, 2) . '-' . substr($value, 3, 2)) < 0) {
$age--;
}
if( $age < $minimum_age ){
$result["is_valid"] = false;
$result["message"] = "Sorry, you must be at least $minimum_age years old. You're $age years old.";
}
}
//Check if dob field is empty
if(empty($value)){
$result["is_valid"] = false;
$result["message"] = "This field is required.";
}
return $result;
}
I'm using Gravity Forms 1.8.8 and latest Wordpress and works as desired. Screenshot:
You can also edit this according to form and field:
add_filter("gform_field_validation_1_1", "dob_validate", 10, 4);
Where gform_field_validation_1_1
is for form 1 and field 1. If your forms id is 8 and field number is 2, you can change it to gform_field_validation_8_2
.
You can also add that same filter multiple times for multiple forms and fields without recreating the dob_validate
function.