Skip to content

Instantly share code, notes, and snippets.

@maddisondesigns
Created September 29, 2014 08:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save maddisondesigns/4ed1203330e15a4443a9 to your computer and use it in GitHub Desktop.
Save maddisondesigns/4ed1203330e15a4443a9 to your computer and use it in GitHub Desktop.
Custom Gravity Forms Dropdown Validation
<?php
/**
* 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' );
@pandglobal
Copy link

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