如何验证URL并排除某些域

时间:2014-03-11 08:40:23

标签: ruby-on-rails

我有一个存储网址的模型,但我想排除一些指定的网址,例如:http://google.com。这是模型:

class Link < ActiveRecord::Base
  validates :url, presence: true
  validates :url, format: { with: /\Ahttps?:\/\//,
                            without: Regexp.new("http://google.com") }
end

但是我收到了这条错误消息:

Either :with or :without must be supplied (but not both)

如何为此编写验证?

2 个答案:

答案 0 :(得分:2)

您可以将其分为两个验证

validates :url, format: { with: /\Ahttps?:\/\//}
validates :url, format: { without: Regexp.new("http://google.com") }

答案 1 :(得分:0)

试试这个

validates :url, format: { with: /\Ahttps?:\/\//}
validates :url, exclusion: { in: %w(google) }