0

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?

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

I chose your solution and adapted it. Works great.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.