I use multi page gravity forms. The code below checks first page and I can't click next
button because the field is in second page and its not valid correctly. I tried with $current_page == 2
but it doesn't work for me and I don't know why.
Peace of code below. It would be nice if someone could give me a helping hand
// validate 9 digit code
// change here to your form ID
add_filter('gform_validation_1', 'validate_code');
function validate_code($validation_result){
// this assumes the code is entered in field one on your form
// change this input_ number if it's a different field
if(!is_code_valid($_POST['input_18'])) {
$validation_result['is_valid'] = false;
foreach($validation_result['form']['fields'] as &$field){
// field 1 is the field where we want to show the validation message
if($field['id'] == 18){
$field['failed_validation'] = true;
$field['validation_message'] = 'The code you entered is invalid: please try again.';
break;
}
}
}
return $validation_result;
}
// use this function to validate codes
function is_code_valid($thiscode){
// read all the codes in from the numbers.txt file
// change the path here to the location of your file
$codes = file('/htdocs/homepages/99/numbers.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach($codes as $code){
// compare the entered code to all codes in the file until we find a match
if($thiscode == $code){
return TRUE;
}
}
// if we did not have a match and are out of codes, return FALSE
return FALSE;
}
// doing this here because the redirect URL does not support variables or shortcodes
// change the 70 here to your form ID
add_filter('gform_confirmation_1', 'valid_invitation_confirmation', 10, 4);
function valid_invitation_confirmation($confirmation, $form, $lead, $ajax){
// customize this URL - I send the code in the query string
$success_url = get_bloginfo('url') . '/?code=' . $lead[1];
$confirmation = array('redirect' => $success_url);
return $confirmation;
}
As you've realized, you only want to validate the field when the form page that contains it is submitted. Here is how can you check for that:
if( $field['pageNumber'] == GFFormDisplay::get_source_page($form['id'] ) ) {
// run your custom validation here
}
This would go inside the $fields foreach loop. You can see this in action on one of my snippets.