The gform_validation action allows custom validation logic to be used by Gravity Forms when a form is submitted.
Usage
add_filter('gform_validation', 'custom_validation', 10, 2);
Parameters
$validation_result
(array) – Contains the validation result and the current Form Object.$context
(string) – The context for the current submission. Since Gravity Forms 2.6.3.2. Possible values:form-submit
,api-submit
, orapi-validate
.
More information
See Gravity Forms Docs: gform_validation
Examples
Validate a specific field
This example prevents a specific number (86) from being entered in a field with ID 1.
add_filter('gform_validation', 'custom_validation'); function custom_validation($validation_result) { $form = $validation_result['form']; if (rgpost('input_1') == 86) { $validation_result['is_valid'] = false; foreach ($form['fields'] as &$field) { if ($field->id == '1') { $field->failed_validation = true; $field->validation_message = 'This field is invalid!'; break; } } } $validation_result['form'] = $form; return $validation_result; }
Send entry data to third-party
This example demonstrates a simple approach to posting submitted entry data to a third-party application. The response is used to determine the form validation result.
add_filter('gform_validation', 'post_to_third_party'); function post_to_third_party($validation_result) { $form = $validation_result['form']; $entry = GFFormsModel::get_current_lead(); $post_url = 'http://thirdparty.com'; $body = array( 'first_name' => rgar($entry, '1.3'), 'last_name' => rgar($entry, '1.6'), 'message' => rgar($entry, '3'), ); $request = new WP_Http(); $response = $request->post($post_url, array('body' => $body)); if (/* check something in the $response */) { $validation_result['is_valid'] = false; foreach ($form['fields'] as &$field) { if ($field->id == '1') { $field->failed_validation = true; $field->validation_message = 'This field is invalid!'; break; } } } $validation_result['form'] = $form; return $validation_result; }
Abort Submission if Total is Zero
This example prevents the form submission if the Total field (id 3) is equal to zero.
add_action('gform_validation', function($validation_result) { $form = $validation_result['form']; if (10 != $form['id']) { return $validation_result; } if ('$0.00' === rgpost('input_3')) { $validation_result['is_valid'] = false; foreach ($form['fields'] as &$field) { if ($field->type == 'total') { $field->failed_validation = true; $field->validation_message = 'You must select at least one product!'; break; } } } $validation_result['form'] = $form; return $validation_result; });