0

好的。

1)我需要:link在我的模型中进行验证,并且只有在它不为空白(或为零)时才这样做。

2)如果:link不是空白并且标准验证通过 - 我需要运行我的自定义验证方法来检查 URL 可用性。

通过“标准”验证,我的意思是这样的:

validates :link, :presence => true, :uniqueness => true, 
                 :format => { :with => /^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/ix }

实现这一点的正确方法是什么?

4

3 回答 3

0
validates_format_of :url_field, :with => URI::regexp(%w(http https))
于 2011-08-24T08:29:35.310 回答
0

好的。在朋友的帮助下,我终于解决了这个问题。

class Post < ActiveRecord::Base

  # skipped some things not necessary 

  validates_format_of :link, :with => /^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/ix , :allow_blank => true
  validates_length_of :link, :maximum => 2000
  validates_uniqueness_of :link, :allow_blank => true

  validate :ensure_link_is_available, :if => proc{|post| post.link.present? && post.errors.empty?}

  def ensure_link_is_available
    begin
      require "net/http"
      url = URI.parse(self.link)
      req = Net::HTTP.new(url.host, url.port)
      res = req.request_head(url.path)
    rescue
      # error occured, add error
      self.errors.add(:link, 'The requested URL could not be retrieved')
    else
      # valid site
      if (res.code.to_i > 308) 
        error_message = 'Server responded with ' + res.code
        self.errors.add(:link, error_message)
      end
    end
  end                    

end
于 2011-08-25T03:12:53.450 回答
0

仅当链接不为空时,它才会检查模型中的验证:

validates_presence_of :link, :uniqueness => true, 
                      :format => { :with => /^(http|https)://[a-z0-9]+([-.]{1}[a-z0-9]+).[a-z]{2,5}(:[0-9]{1,5})?(/.)?$/ix }, :if => :link_present?

def link
  self.link
end

def link_present?
  link.present?
end
于 2011-08-24T04:51:45.033 回答