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.
There is good reason for this, the protocol needs to be known so the value can become a clickable link where the entry is displayed – and it is difficult to assume that the protocol will be one.
There is another limitation to the ‘website’ field – if the user provides an invalid URL (that includes a valid protocol) – for example http://google.google the field will validate – resulting in bad information provided in the entry.
Solution
The code below solves these issue by:
- if the value does not include a protocol – assume it is http:// and automatically add it to the value
- check the URL and display an error message if it does not link to a valid page (either does not load or loads a 404 error page).
If the URL does not link to a valid page, a custom error message which reads ‘There was an error loading the website address – check the link and try again.’ is displayed.
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 $form_id = $form['id']; // get the form 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 } $check_value = get_headers($value); // load url and get headers if( $check_value == FALSE || strpos($check_value[0], '404') == TRUE ) { // if header returned was an error or contained a 404 response code add_filter( 'gform_field_validation_'.$form_id.'_'.$field_id, 'itsg_url_not_valid', 10, 4 ); // set the field as not valid } $_POST['input_' . $field_id] = $value; // update post with new value } } } return $form; } function itsg_url_not_valid( $result, $value, $form, $field ) { $result['is_valid'] = false; // set the field as not valid $result['message'] = 'there was an error loading the website address - check the link and try again.'; // custom error message when URL did not load return $result; }