bookmark_bordergform_pre_validation

Description

This filter can be used to manipulate the used during the form validation process.

Usage

The following would apply to all forms.

add_filter( 'gform_pre_validation', 'your_function_name' );

To limit the scope of your function to a specific form, append the form id to the end of the hook name. (format: gform_pre_validation_FORMID)

add_filter( 'gform_pre_validation_6', 'your_function_name' );

Parameters

  • $form

    The current form to be filtered.

Examples

1. Conditionally Required Field

The following example shows how you can conditionally require a field based on the value of another field.

add_filter( 'gform_pre_render', 'gw_conditional_requirement' );
add_filter( 'gform_pre_validation', 'gw_conditional_requirement' );
function gw_conditional_requirement( $form ) {
    $value = rgpost( 'input_2' );
    if ( $value == 'no' ) {
        return $form;
    }

    foreach ( $form['fields'] as &$field ) {
        if ( $field->id == 1 ) {
            $field->isRequired = true;
        }
    }
    return $form;
}

2. Populate Choices – Drop Down

This example dynamically populates a drop down field with posts that are in the Business category.

add_filter( 'gform_pre_validation', 'populate_dropdown' );
function populate_dropdown( $form ) {

    //only populating drop down for form id 5
    if ( $form['id'] != 5 ) {
       return $form;
    }

    //Reading posts for "Business" category;
    $posts = get_posts( 'category=' . get_cat_ID( 'Business' ) );

    //Creating drop down item array.
    $items = array();

    //Adding initial blank value.
    $items[] = array( 'text' => '', 'value' => '' );

    //Adding post titles to the items array
    foreach ( $posts as $post ) {
        $items[] = array( 'value' => $post->post_title, 'text' => $post->post_title );
    }

    //Adding items to field id 8. Replace 8 with your actual field id. You can get the field id by looking at the input name in the markup.
    foreach ( $form['fields'] as &$field ) {
        if ( $field->id == 8 ) {
            $field->choices = $items;
        }
    }

    return $form;
}

Placement

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

Source Code

$form = gf_apply_filters( 'gform_pre_validation', $form['id'], $form );

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

Since

This filter was added in Gravity Forms 1.9.