bookmark_bordergform_field_validation

Description

Use this filter to create custom validation logic for a field.

Usage

The base filter which applies to all forms and all fields would be used like so:

add_filter( 'gform_field_validation', 'your_function_name', 10, 4 );

You can also target all fields in a form by adding the form id after the hook name.

//The following declaration targets all fields in form 6
add_filter( 'gform_field_validation_6', 'your_function_name', 10, 4 );

You can also target a specific field by adding the form id and field id after the hook name.

//The following declaration targets field 1 in form 6
add_filter( 'gform_field_validation_6_1', 'your_function_name', 10, 4 );

Parameters

  • $result array

    The validation result to be filtered. It is formatted as follows:

        array( 'is_valid' => false, 'message' => 'Please enter a number greater than 10' )
        

  • $value string | array

    The field value to be validated. Multi-input fields like Address will pass an array of values.

  • $form

    Current Form object.

  • $field Field Object

    Current Field object.

Examples

1. Number field validation

This example validates a field so that only numbers less than 10 are allowed.

add_filter( 'gform_field_validation_175_1', 'custom_validation', 10, 4 );
function custom_validation( $result, $value, $form, $field ) {

    if ( $result['is_valid'] && intval( $value ) > 10 ) {
        $result['is_valid'] = false;
        $result['message'] = 'Please enter a value less than 10';
    }
    return $result;
}

2. Price field validation

This example validates a price field to make sure the user entered an amount of at least 3000.

add_filter( 'gform_field_validation_116_1', 'custom_validation', 10, 4 );
function custom_validation( $result, $value, $form, $field ) {
    //change value for price field to just be numeric (strips off currency symbol, etc.) using Gravity Forms to_number function
    //the second parameter to to_number is the currency code, ie "USD", if not specified USD is used
    $number = GFCommon::to_number( $value, '' );

    if ( $result['is_valid'] && intval( $number ) < 3000 ) {
        $result['is_valid'] = false;
        $result['message'] = 'You must enter at least $3,000.';
    }
    return $result;
}

3. Address field validation

This example validates the address field so that you can control which parts are required. Only the street, city, and state are required in this example.

add_filter( 'gform_field_validation_224_1', 'custom_address_validation', 10, 4 );
function custom_address_validation( $result, $value, $form, $field ) {
    //address field will pass $value as an array with each of the elements as an item within the array, the key is the field id
    if ( ! $result['is_valid'] && $result['message'] == 'This field is required. Please enter a complete address.' ) {
        //address failed validation because of a required item not being filled out
        //do custom validation
        $street  = rgar( $value, $field->id . '.1' );
        $street2 = rgar( $value, $field->id . '.2' );
        $city    = rgar( $value, $field->id . '.3' );
        $state   = rgar( $value, $field->id . '.4' );
        $zip     = rgar( $value, $field->id . '.5' );
        $country = rgar( $value, $field->id . '.6' );
        //check to see if the values you care about are filled out
        if ( empty( $street ) && empty( $city ) && empty( $state ) ) {
            $result['is_valid'] = false;
            $result['message']  = 'This field is required. Please enter at least a street, city, and state.';
        } else {
            $result['is_valid'] = true;
            $result['message']  = '';
        }
    }

    return $result;
}

This example validates the zip input of field 1 on form 2.

add_filter( 'gform_field_validation_2_1', 'custom_zip_validation', 10, 4 );
function custom_zip_validation( $result, $value, $form, $field ) {
	if ( $result['is_valid'] ) {
		$acceptable_zips = array(
			'123',
			'456'
		);

		$zip_value = rgar( $value, $field->id . '.5' );

		if ( ! in_array( $zip_value, $acceptable_zips ) ) {
			$result['is_valid'] = false;
			$result['message']  = 'Zip validation failed.';
		}
	}

	return $result;
}

4. Name field validation

This example validates all the Name field inputs which are not hidden, the default validation only requires the first and last inputs.

add_filter( 'gform_field_validation', function ( $result, $value, $form, $field ) {
    if ( $field->type == 'name' ) {

        // Input values
        $prefix = rgar( $value, $field->id . '.2' );
        $first  = rgar( $value, $field->id . '.3' );
        $middle = rgar( $value, $field->id . '.4' );
        $last   = rgar( $value, $field->id . '.6' );
        $suffix = rgar( $value, $field->id . '.8' );

        if ( empty( $prefix ) && ! $field->get_input_property( '2', 'isHidden' )
             || empty( $first ) && ! $field->get_input_property( '3', 'isHidden' )
             || empty( $middle ) && ! $field->get_input_property( '4', 'isHidden' )
             || empty( $last ) && ! $field->get_input_property( '6', 'isHidden' )
             || empty( $suffix ) && ! $field->get_input_property( '8', 'isHidden' )
        ) {
            $result['is_valid'] = false;
            $result['message']  = empty( $field->errorMessage ) ? __( 'This field is required. Please enter a complete name.', 'gravityforms' ) : $field->errorMessage;
        } else {
            $result['is_valid'] = true;
            $result['message']  = '';
        }
    }

    return $result;
}, 10, 4 );

5. Compare value against another field.

This example validates field 2 to make sure the value does not match field 1.

add_filter( 'gform_field_validation_10_2', function ( $result, $value, $form, $field ) {
    $master = rgpost( 'input_1' );
    if ( $result['is_valid'] && $value == $master ) {
        $result['is_valid'] = false;
        $result['message']  = 'Please enter a different email.';
    }

    return $result;
}, 10, 4 );

6. Phone field validation

This example shows how you can use regex to validate the value of phone field.

add_filter( 'gform_field_validation', 'validate_phone', 10, 4 );
function validate_phone( $result, $value, $form, $field ) {
	$pattern = "/^(\+44\s?7\d{3}|\(?07\d{3}\)|\(?01\d{3}\)?)\s?\d{3}\s?\d{3}$/";
	if ( $field->type == 'phone' && $field->phoneFormat != 'standard' && ! preg_match( $pattern, $value ) ) {
		$result['is_valid'] = false;
		$result['message']  = 'Please enter a valid phone number';
	}

	return $result;
}

7. Time field validation

This example validates field 2 in form 1 to check that time is between two set times (12 hour time format).

add_filter( 'gform_field_validation_1_2', 'validate_time', 10, 4 );
function validate_time( $result, $value, $form, $field ) {
    //convert the entire time field array into a string, separating values with colons
    $input_time = implode( ':', $value );
    //replace colon between the time and am/pm with space and convert strings into a unix timestamp
    $time = strtotime( substr_replace( $input_time, ' ', -3, 1 ) );
    $max_time = strtotime( '17:00' );
    $min_time = strtotime( '09:00' );

    if ( $time < $min_time OR $time > $max_time ) {
        $result['is_valid'] = false;
        $result['message'] = 'Please select a time between 09:00 am and 05:00 pm';
    }
    return $result;
}

8. Check if email is on MailChimp list

The following example shows how you return an error if the email is already on a MailChimp list.

add_filter( 'gform_field_validation', function ( $result, $value, $form, $field ) {
	if ( $field->type == 'email' && $result['is_valid'] && class_exists( 'GF_MailChimp_API' ) ) {
		gf_mailchimp()->log_debug( 'gform_field_validation: running.' );
		$api_key = gf_mailchimp()->get_plugin_setting( 'apiKey' );

		if ( rgblank( $api_key ) ) {
			gf_mailchimp()->log_debug( 'gform_field_validation: aborting; no api key.' );
			return $result;
		}

		$entry   = GFFormsModel::get_current_lead();
		$feeds   = gf_mailchimp()->get_single_submission_feed_by_form( $form, $entry );
		$list_id = rgars( $feeds, '0/meta/mailchimpList' );

		if ( empty( $list_id ) ) {
			gf_mailchimp()->log_debug( 'gform_field_validation: aborting; no list id.' );
			return $result;
		}

		try {

			// Get member info.
			$mc_api = new GF_MailChimp_API( $api_key );
			$member = $mc_api->get_list_member( $list_id, $value );

			// Set member status.
			$member_status = $member['status'];

		} catch ( Exception $e ) {

			// The email is not on the list or there was an API issue.
			$member_status = false;

		}

		gf_mailchimp()->log_debug( 'gform_field_validation: member status => ' . print_r( $member_status, 1 ) );

		if ( $member_status == 'subscribed' ) {
			$result['is_valid'] = false;
			$result['message']  = empty( $field->errorMessage ) ? 'This address is already on the list.' : $field->errorMessage;
		}
	}

	return $result;
}, 10, 4 );

9. Date field validation

The following example shows how you override the default validation when using a custom date format.

add_filter( 'gform_field_validation', 'custom_date_validation', 10, 4 );
function custom_date_validation( $result, $value, $form, $field ) {
	if ( ! $result['is_valid'] && $field->get_input_type() == 'date' ) {
		$date = GFCommon::parse_date( $value );

		if ( ! GFCommon::is_empty_array( $date ) && checkdate( $date['month'], $date['day'], $date['year'] ) ) {
			$result['is_valid'] = true;
			$result['message']  = '';
		} else {
			$result['message'] = 'Please enter a valid date.';
		}
	}

	return $result;
}

10. Product field quantity validation

The following example shows how you perform custom validation of the product field quantity input. This example is validating that the quantity input of field 1 on form 10 contains a value less than 10.

add_filter( 'gform_field_validation_10_1', 'product_quantity_validation', 10, 4 );
function product_quantity_validation( $result, $value, $form, $field ) {
	$quantity = intval( rgar( $value, $field->id . '.3' ) );

	if ( $result['is_valid'] && $quantity > 10 ) {
		$result['is_valid'] = false;
		$result['message']  = 'Please enter a value less than 10';
	}

	return $result;
}

11. Email validation by third-party API

The following example shows how you can send the value of an Email type field to a third-party API to determine if the email is valid. In this example we are using the QuickEmailVerification API.

add_filter( 'gform_field_validation', function ( $result, $value, $form, $field ) {
	if ( $field->get_input_type() === 'email' && $result['is_valid'] ) {
		$request_url = add_query_arg(
			array(
				'email'  => $value,
				'apikey' => 'your_api_key_here',
			),
			'http://api.quickemailverification.com/v1/verify'
		);

		$response       = wp_remote_get( $request_url );
		$response_json  = wp_remote_retrieve_body( $response );
		$response_array = json_decode( $response_json, 1 );

		if ( rgar( $response_array, 'result' ) !== 'valid' ) {
			$result['is_valid'] = false;
			$result['message']  = 'Email is invalid';
		}
	}

	return $result;
}, 10, 4 );

Placement

This code should be placed in the functions.php file of your active theme.

Source Code

This filter is located in GFFormDisplay::validate() in form_display.php