重力形式 - gform_validation - 如果多个复选框字段为空,则无效

时间:2017-03-21 15:37:25

标签: php wordpress forms gravity-forms-plugin

我有这个函数来验证重力形式。它检查两个单独的复选框字段是否为空,如果是,则阻止用户提交表单:

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;
    }
}

验证有效,但是当我提交带有复选框的表单时,它会声明'糟糕!我们无法找到您的表单。':

Working Example

不确定我是否使用正确的方法检查两个字段是否为空。

1 个答案:

答案 0 :(得分:1)

我通过将return $validation_result;移到if语句之外来修复此问题:

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;
}

表单现在在检查某些复选框字段是否为空后提交。