Jonathan Clark
Jonathan Clark

Reputation: 20538

Rails 3 and validating if http is included in link

When a user submits a link, is there a way to validate if he have included the http:// or not. I other words, is it possible to not only validate but also add the http:// if it is missing?

I am using Rails 3.

Upvotes: 0

Views: 660

Answers (3)

Lukasz Muzyka
Lukasz Muzyka

Reputation: 2783

variation on Steve Lorek's answer taking in the account that some links submitted by user will contain https:// instead of http://

def link=(str)
  str = 'http://' + str if (str[0,7] != 'http://' && str[0,8] != 'https://')
  super(str)
end

Upvotes: 0

Steve Lorek
Steve Lorek

Reputation: 111

You could override the setter method for the link. In your model, something like this:

def link=(str)
  str = 'http://' + str if str[0,7] != 'http://'
  super(str)
end

This would force adding http:// to the start of all links if not already there.

Upvotes: 3

Sinetris
Sinetris

Reputation: 8945

You can use a custom validation.

Pretending your model is "Post" and the attribute is "url" you can use something like:

class Post < ActiveRecord::Base
  validate :ensure_valid_url

  protected

  def ensure_valid_url
    protocol_regexp =  %r{
      \A
      (https?://)
      .*
      \Z
    }iux

    self.url = "http://" + url unless url.blank? or url.match(protocol_regexp)

    ipv4_part = /\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]/  # 0-255
    regexp = %r{
      \A
      https?://
      ([^\s:@]+:[^\s:@]*@)?
      ( (xn--)?[[:alnum:]\w_]+([-.][[:alnum:]\w_]+)*\.[a-z]{2,6}\.? |
          #{ipv4_part}(\.#{ipv4_part}){3} )
      (:\d{1,5})?
      ([/?]\S*)?
      \Z
    }iux

    default_message     = 'does not appear to be a valid URL'
    default_message_url = 'does not appear to be valid'
    options = { :allow_nil => false,
                :allow_blank => false,
                :with => regexp }

    message =  url.to_s.match(/(_|\b)URL(_|\b)/i) ? default_message_url : default_message
    validates_format_of(:url, { :message => message }.merge(options))
  end

end

This example is based on validates_url_format_of

Upvotes: 2

Related Questions