How to make at least one of many fields required

By default Gravity Forms only allows you to set a field as required or not.

You can control this to some extent by using conditional logic to show or hide the field – but what if you need a group of fields and make one of either of them required. For example, three phone number fields and any one of them is required? The code below shows how to do this.

Want to see it in action – check out the demo at: http://demo.gravitygeek.com/at-least-one-phone-number-required/

If you’re not sure where to place this code I highly recommend you read How to create a WordPress plugin for your custom functions.

// NOTE: replace 4 with the form ID
add_filter( 'gform_validation_4', 'custom_validation' );
function custom_validation( $validation_result ) {
    $form = $validation_result['form'];

    // if one of the required fields are required
    // NOTE: replace 1, 2, 3 with the fields you would like to validate
    if ( empty( rgpost( 'input_1' ) ) && empty( rgpost( 'input_2' ) ) && empty( rgpost( 'input_3' ) ) ) {

        //finding Field with ID of 1 and marking it as failed validation
        foreach( $form['fields'] as &$field ) {

            // NOTE: replace 1, 2, 3 with the fields you would like to validate
            if ( $field->id == '1' || $field->id == '2' || $field->id == '3' ) {
                $field->failed_validation = true;
                $field->validation_message = 'At least one phone number must be provided.';
                $validation_result['is_valid'] = false;
            }
        }
    }
    // Assign modified $form object back to the validation result
    $validation_result['form'] = $form;
    return $validation_result;
}

Was this article helpful?

Related Articles