Hey I've been reading through the gform_validation_hook tutorial repeatedly and I just can't seem to make the connection from the example given to the goal that I have in mind.
I basically want to create a birth date validator that would suspend the registration process if the supplied birthday doesn't add up to the age of 21 (on December 8, 2011).
Here's the link to my form: http://motormediausa.com/test/
And here's my code:
// CUSTOM AGE VERIFICATION
add_filter( 'gform_validation_1', 'age_validation');
function age_validation($validation_result){
$form = $validation_result['form'];
foreach($form['fields'] as &$field){
// 5 - If the field does not have our designated CSS class, skip it
if(strpos($field['cssClass'], 'validate-age') === false)
continue;
// 7 - Check if the field is hidden by GF conditional logic
$is_hidden = RGFormsModel::is_field_hidden($form, $field, array());
// 8 - If the field is not on the current page OR if the field is hidden, skip it
if($field_page != $current_page || $is_hidden)
continue;
// 9 - Get the submitted value from the $_POST
$field_value = rgpost("input_{$field['id']}");
// 10 - Make a call to your validation function to validate the value
$is_valid = is_age($field_value);
// 11 - If the field is valid we don't need to do anything, skip it
if($is_valid)
continue;
// 12 - The field field validation, so first we'll need to fail the validation for the entire form
$validation_result['is_valid'] = false;
// 13 - Next we'll mark the specific field that failed and add a custom validation message
$field['failed_validation'] = true;
$field['validation_message'] = 'The birthday you have entered indicates that you are not of legal drinking age and will be ineligible to compete in this tournament.';
}
// 14 - Assign our modified $form object back to the validation result
$validation_result['form'] = $form;
// 15 - Return the validation result
return $validation_result;
}
function is_age($age) {
$day = ("#input_1_3_2");
$month = ("#input_1_3_1");
$year = ("#input_1_3_3");
$age = 21;
$mydate=new Date();
mydate.setFullYear(1990,11-1,8);
$currdate = new Date();
currdate.setFullYear(currdate.getFullYear() - age);
if ((currdate - mydate) < 0){
alert("Sorry, only persons over the age of " + age + " may enter this competition.");
return false;
}
return true;
};
Any help that you could provide would be excellent. Thank you.
Posted 13 years ago on Tuesday November 8, 2011 |
Permalink