Is it possible to use validates_exclusion_of with regular expressions?
That would ensure that URLs matching these specific patterns can't be validated nor inserted into db.
What would be the best approach to code this?
There are a couple ways I might do it, depending on the circumstance.
First, if I am going to have to match some patterns and then exclude others I might do something like this:
validates_format_of :url, :with => /swanky pattern/, :unless => :beavis
def beavis
self.url.match(/beavis/)
end
Or if you just need to exclude certain patterns
validate :i_hate_beavis
def i_hate_beavis
errors.add(:url, 'cannot be beavis') if self.url.match(/beavis/)
end
resources: http://apidock.com/rails/ActiveModel/Validations/ClassMethods/validate
I took Geoff's approach and implemented the following:
validate :url_is_acceptable
URL_BLACKLIST = [
/http:\/\/www.some-website.com\/.*/,
/http:\/\/www.other-website.com\/.*/
]
def url_is_acceptable
URL_BLACKLIST.each do |blacklisted_url|
if self.url =~ blacklisted_url
errors.add(:not_acceptable, "is not acceptable")
return
end
end
end