Introduction
The GFAPI::validate_field()
method, added in Gravity Forms 2.7, is used to validate the input values of a specific field. This method can trigger the following filters:
If you need to validate all or most fields of a form see Validating Form Submissions with the GFAPI.
Source Code
public static function validate_field( $form_id, $field_id, $input_values = array() ) {}
This method is located in /includes/api.php.
Parameters
Param | Type | Description |
---|---|---|
$form_id | integer | The ID of the form this submission belongs to. |
$field_id | integer | The ID of the field to be validated. |
$input_values | array | An associative array containing the values to be validated using the field input names as the keys. Will be merged into the $_POST .The expected input names are identical to the input names found in the form markup. If you have any doubts about the name of an input, use your browsers developer tools to inspect the inputs via the form preview page. |
Returns
An associative array containing the result properties or a WP_Error instance if the form can’t be found, isn’t active, is trashed, doesn’t have any fields, the field can’t be found, or the field doesn’t support validation.
Key | Type | Description |
---|---|---|
is_valid | bool | The field validation result. |
message | string | The field validation message, if invalid. |
Usage Examples
This is a basic usage example showing how to pass the parameters and how to handle the returned result.
$result = GFAPI::validate_field( $form_id, $field_id, $input_values );
if ( is_wp_error( $result ) ) {
$error_message = $result->get_error_message();
// Do something with the error message.
} elseif ( ! rgar( $result, 'is_valid' ) ) {
$error_message = rgar( $result, 'message' );
// Do something with the error message.
} else {
// Do something with the valid values.
}
Validate multi-input field type
This example shows how you would define the parameters when needing to validate a multi-input field type. In this case a name field with the id 2 belonging to form id 1.
$form_id = 1;
$field_id = 2;
$input_values = array();
$input_values['input_2_3'] = 'First name';
$input_values['input_2_6'] = 'Last name';
$result = GFAPI::validate_field( $form_id, $field_id, $input_values );
Compare value against another field
Submitting the values from multiple fields is supported but out of the box only the values of the field matching the specified $field_id
will be validated. This can be used to allow the gform_field_validation filter (e.g. example 5) to compare the values of multiple fields.
$form_id = 10;
$field_id = 2;
$input_values = array();
$input_values['input_1'] = 'field 1 value';
$input_values['input_2'] = 'field 2 value';
$result = GFAPI::validate_field( $form_id, $field_id, $input_values );
Since
This method was added in Gravity Forms 2.7.