Gravity Forms – How to automatically add HTTP:// to submitted website field values before validation

Problem

By default, ‘website’ fields in Gravity Forms will display a validation error message if the user enters an address that is missing the protocol – HTTP, HTTPS, FTP.

The script below will check the value submitted before it is validated and add HTTP:// if it is missing.

If you want to verify the URL as well see — Gravity Forms – ‘Please enter a valid Website URL’ validation error when value missing protocol HTTP HTTPS FTP

 GravityForms-WebsiteFieldHTTP1

Solution

The code below will:

  1. check for ‘website’ fields in a submitted form
  2. if the field value does not include a protocol – assume it is http:// and automatically add it to the value

To install the code either add it to your theme’s functions.php file, below the opening <?php line or create your own custom functions plugin and add it there.

add_filter( 'gform_pre_render', 'itsg_check_website_field_value' );
add_filter( 'gform_pre_validation', 'itsg_check_website_field_value' );
function itsg_check_website_field_value( $form ) {
    foreach ( $form['fields'] as &$field ) {  // for all form fields
        if ( 'website' == $field['type'] || ( isset( $field['inputType'] ) && 'website' == $field['inputType']) ) {  // select the fields that are 'website' type
            $value = RGFormsModel::get_field_value($field);  // get the value of the field
            if (! empty($value) ) { // if value not empty
                $field_id = $field['id'];  // get the field id
                if (! preg_match("~^(?:f|ht)tps?://~i", $value) ) {  // if value does not start with ftp:// http:// or https://
                    $value = "http://" . $value;  // add http:// to start of value
                }

                $_POST['input_' . $field_id] = $value; // update post with new value
            }
        }
    }
    return $form;