开发者

Rails 3 and validating if http is included in link

开发者 https://www.devze.com 2023-01-26 06:01 出处:网络
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 poss开发者_开发问答ible to not only validate but also add the http:// if it is missi

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 poss开发者_开发问答ible to not only validate but also add the http:// if it is missing?

I am using Rails 3.


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.


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消