I'm using PHP to check for a very specific error condition and I've tried to return an updated value without success.

I'm assuming this module wasn't designed for this use case, but perhaps I'm overlooking something.

I'd like to check a URL for a 'http://' and if missing, add it, ala:

if ((strpos($this->value, "http://") == false) && (strpos($this->value, "https://") == false)) {
  $this->value = 'http://' . $this->value;
  return $this->value;
}

Comments

bisonbleu’s picture

Category: support » task

I second this request and have changed the category to 'task'.

By default, the Link module will add the 'http://' if it is missing. This makes it more user friendly for average folks. I think 'Field validation', which does great things for admins, should build on this simple expectation and do the same.

The 'Link' module does it this way. Would this work for 'Field validation' ?

/**
 * Forms a valid URL if possible from an entered address.
 * 
 * Trims whitespace and automatically adds an http:// to addresses without a
 * protocol specified
 *
 * @param string $url
 * @param string $protocol
 *   The protocol to be prepended to the url if one is not specified
 */
function link_cleanup_url($url, $protocol = 'http') {
  $url = trim($url);
  $type = link_validate_url($url);

  if ($type === LINK_EXTERNAL) {
    // Check if there is no protocol specified.
    $protocol_match = preg_match("/^([a-z0-9][a-z0-9\.\-_]*:\/\/)/i", $url);
    if (empty($protocol_match)) {
      // But should there be? Add an automatic http:// if it starts with a domain name.
      $LINK_DOMAINS = _link_domains();
      $domain_match = preg_match('/^(([a-z0-9]([a-z0-9\-_]*\.)+)(' . $LINK_DOMAINS . '|[a-z]{2}))/i', $url);
      if (!empty($domain_match)) {
        $url = $protocol . "://" . $url;
      }
    }
  }

  return $url;
}
g089h515r806’s picture

It seems that we could not change field value in hook_field_attach_validate.
Maybe we could change it in other hooks.

g089h515r806’s picture

Issue summary: View changes
Status: Active » Closed (outdated)