Skip to content

Instantly share code, notes, and snippets.

@getdave
Last active January 30, 2024 06:34
Show Gist options
  • Save getdave/4578295 to your computer and use it in GitHub Desktop.
Save getdave/4578295 to your computer and use it in GitHub Desktop.
Gravity Forms - custom field validation function for checkboxes. Ensures all checkboxes have been checked.
// Replace 7 with the ID of your form and 13 with the ID of the field you want to force "all required"
// http://www.gravityhelp.com/documentation/page/Gform_field_validation
add_filter("gform_field_validation_7_13", 'validate_tcs', 10, 4);
function validate_tcs($result, $value, $form, $field) {
// Convert the checkbox input name value (returned as part of "field")
// into the "underscored" ID version which is found in the $_POST
foreach ($field['inputs'] as $input) {
$input_post_value = 'input_' . str_replace('.', '_', $input['id']);
// Validate the value
if ( !isset( $_POST[$input_post_value] ) ) {
$result["is_valid"] = false;
$result["message"] = "You must accept <em>all</em> of the Terms and Conditions";
}
}
return $result;
}
@jasimp
Copy link

jasimp commented Jan 30, 2024

hi
how to exempt hidden check boxes that made hidden by conditional logics through java script

tried the below but not succeeded

    // Check if the choice input is hidden using inline style
    $is_hidden = isset($input['cssClass']) && strpos($input['cssClass'], 'hidden-choice') !== false;

    // Check if the choice input is hidden using inline style (display: none)
    $is_display_none = isset($input['attributes']['style']) && strpos($input['attributes']['style'], 'display: none;') !== false;

    // Validate the value only if the choice input is not hidden
    if (!$is_hidden && !$is_display_none && !isset($_POST[$input_post_value])) {
        $result["is_valid"] = false;
        $result["message"] = "You must accept <em>all</em> of the Terms and Conditions";
    }
}        

return $result;
}

=====================================
Below is the hidden element

<div class="gchoice gchoice_13_42_6">
    <input class="gfield-choice-input" name="input_42.6" type="checkbox" value="Letter submitted" id="choice_13_42_6" style="display: none;">
    <label for="choice_13_42_6" id="label_13_42_6" class="gform-field-label gform-field-label--type-inline" style="display: none;">Letter submitted</label>
</div>

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment