Simon
Simon

Reputation: 1125

Gravity Form - gform_validation - Invalidate if multiple checkbox fields are empty

I have this function which validates a gravity form. It checks if two separate check box fields are empty, if they are, prevent the user from submitting the form:

add_filter( 'gform_validation_16', 'check_for_age_group' );
function check_for_age_group( $validation_result ) {
    if(empty($_POST["input_31_1"]) && empty($_POST["input_12_1"])){
        $form = $validation_result['form'];
        // set the form validation to false
        $validation_result['is_valid'] = false;
        //Find the fields and set message validation
        foreach( $form['fields'] as &$field ) {
                if ( $field->id == '31') {
                    $field->failed_validation = true;
                    $field->validation_message = 'Oops! Please select either 55+ Living or All Ages.';
                }
                if ($field->id == '12'){
                    $field->failed_validation = true;
                    $field->validation_message = 'Oops! Please select either 55+ Living or All Ages.';
                }
        }
        //Assign modified $form object back to the validation result
    $validation_result['form'] = $form;
    return $validation_result;
    }
}

The validation works, but when I submit the form with checkboxes checked, it states 'Oops! We could not locate your form.':

Not sure if I am using the correct method for checking that the two fields are empty.

Upvotes: 1

Views: 1208

Answers (1)

Simon
Simon

Reputation: 1125

I fixed this issue by moving the return $validation_result; outside the if statement:

function check_for_age_group( $validation_result ) {
        $form = $validation_result['form'];
        if(empty($_POST["input_31_1"]) && empty($_POST["input_12_1"])){
            // set the form validation to false
            $validation_result['is_valid'] = false;
            //finding Field with ID of 1 and marking it as failed validation
            foreach( $form['fields'] as &$field ) {
                    if ( $field->id == '31') {
                        $field->failed_validation = true;
                        $field->validation_message = 'Oops! Please select either 55+ Living or All Ages.';
                        continue;
                    }
                    if ($field->id == '12'){
                        $field->failed_validation = true;
                        $field->validation_message = 'Oops! Please select either 55+ Living or All Ages.';
                        continue;
                    }
            }
        }
        //Assign modified $form object back to the validation result
        $validation_result['form'] = $form;
        return $validation_result;
}

The form now submits after checking if certain checkbox fields are empty.

Upvotes: 2

Related Questions