flowfree
flowfree

Reputation: 16462

How to validate URLs and exclude certain domains

I have a model to store URLs but I want to exclude some specified domains, e.g: http://google.com. Here is the model:

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

But I got this error messages:

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

How to write the validation for this?

Upvotes: 1

Views: 156

Answers (2)

Pavan
Pavan

Reputation: 33542

Try This

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

Upvotes: 0

Thomas Tran
Thomas Tran

Reputation: 467

You can separate it into two validates

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

Upvotes: 2

Related Questions