在验证期间将www添加到网站URL

tes*_*sad 9 ruby-on-rails

目前,在我的Rails应用程序中通过表单添加URL时,我们有以下内容before_savevalidation检查:

def smart_add_url_protocol
  if self.website?
    unless self.website[/\Ahttp:\/\//] || self.website[/\Ahttps:\/\//]
      self.website = "http://#{self.website}"
    end
  end
end

validates_format_of :website, :with => /^((http|https):\/\/)?[a-z0-9]+([-.]{1}[a-z0-9]+).[a-z]{2,5}(:[0-9]{1,5})?(\/.)?$/ix, :multiline => true
Run Code Online (Sandbox Code Playgroud)

但是,这意味着如果我输入表单字段

testing.com
Run Code Online (Sandbox Code Playgroud)

它告诉我,网址无效,我必须投入

www.testing.com
Run Code Online (Sandbox Code Playgroud)

它接受网址

我希望它接受用户是否输入www或http的URL.

我应该在smart_add_url_protocol中添加其他内容以确保添加它,或者这是验证问题吗?

谢谢

dim*_*ura 9

有一个标准的URI类可用于检查urls.在您的情况下,您需要URI :: regexp方法.使用它你的类可以像这样重写:

before_validation :smart_url_correction
validate :website, :website_validation

def smart_url_correction
  if self.website.present?
    self.website = self.website.strip.downcase
    self.website = "http://#{self.website}" unless self.website =~ /^(http|https)/
  end
end

def website_validation
  if self.website.present?
    unless self.website =~ URI.regexp(['http','https'])
      self.errors.add(:website, 'illegal format')
    end
  end
end
Run Code Online (Sandbox Code Playgroud)