Automatically prepend protocol scheme with URL field module

The URL field module is a great lightweight alternative to the Link module. The module only supports absolute (full path) URLs, which is fine for most purposes, but it annoyingly requires the user to include the protocol scheme (http://) when entering in the URL string. Computers should do these types of menial tasks for us humans, don't you think? ;-)

Luckily there's an easy workaround: add a validation function in a custom module that's called before URL field's validation function. Note: the following assumes you already know how to create a custom module.

First, add the following hook_form_alter function for the appropriate entity type:

/**
* Implements hook_form_alter().
*/
function custom_form_alter(&$form, $form_state, $form_id) {
if ($form_id == 'node_organization_form') {
  array_unshift($form['field_website_link'][LANGUAGE_NONE][0]['value']['#element_validate'], 'custom_url_validate_url');
}

Note: Replace 'node_organization_form' and 'field_website_link' with your form_id and field name respectively.

Second, add the following function to the custom module:

/**
* Prepend http:// to URL string if necessary.
*/
function custom_url_validate_url(&$element, &$form_state) {
  $value = trim($element['#value']);
  if (!empty($value) && strpos($value, 'http://') === FALSE) {
    $element['#value'] = 'http://' . $element['#value'];
  }
}

And there you have it. The URL field module validation will no longer error when the protocol scheme is missing.

But wait, put away that checkbook because there's more! Let's add a placeholder to 'field_website_link' in custom_form_alter:

$form['field_website_link'][LANGUAGE_NONE][0]['value']['#attributes']['placeholder'] = t('http://');

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.