Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Custom Gravity Forms Dropdown Validation
* Custom Gravity Forms validation. Make sure the form isn't submitted with the default dropdown values
* Useful for when your Gravity Form is displaying default values instead of the field labels.
* Tie our validation function to the 'gform_validation' hook. Since we've appended _1 to the filter name (gform_validation_1)
* it will only trigger on form ID 1. Change this number if you want it to trigger on some other form ID.
* There's no sense in running this function on every form submission, now is there!
* @return validation results
function myawesometheme_validate_gravity_default_values( $validation_result ) {
// Get the form object from the validation result
$form = $validation_result["form"];
// Get the current page being validated
$current_page = rgpost( 'gform_source_page_number_' . $form['id'] ) ? rgpost( 'gform_source_page_number_' . $form['id'] ) : 1;
// Loop through the form fields
foreach( $form['fields'] as &$field ){
$value_number = rgpost( "input_{$field['id']}" );
// If the field is a dropdown select field, make sure the first (default) choice isn't selected
if ( $field['type'] === 'select' && $field['choices'][0]['text'] === $value_number ) {
$is_valid = false;
else {
$is_valid = true;
// If the field is valid we don't need to do anything, skip it
if( !$is_valid ) {
// The field failed validation, so first we'll need to fail the validation for the entire form
$validation_result['is_valid'] = false;
// Next we'll mark the specific field that failed and add a custom validation message
$field['failed_validation'] = true;
$field['validation_message'] = "Please select one of the values available.";
// Assign our modified $form object back to the validation result
$validation_result['form'] = $form;
// Return the validation result
return $validation_result;
add_filter( 'gform_validation_1', 'myawesometheme_validate_gravity_default_values' );

This comment has been minimized.

Copy link

@pandglobal pandglobal commented Jan 15, 2020

Nice, thanks for sharing, though what i want exactly is to validate that the user do not submit any value that is not included in the choice field or array.
Am fusing the autopopulate function and i want those values not changed at the front end.
So validation error should read "the value you selected does not exist in the given options"

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