Skip to content

Instantly share code, notes, and snippets.

@leemeichin
Created July 20, 2012 15:02
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save leemeichin/3151191 to your computer and use it in GitHub Desktop.
Save leemeichin/3151191 to your computer and use it in GitHub Desktop.
Rails Custom URL Validator
class UrlValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
record.errors[attribute] << (options[:message] || "must be a valid URL") unless url_valid?(value)
end
# a URL may be technically well-formed but may not actually be
# valid, so this checks for both.
def url_valid?(url)
url = URI.parse(url) rescue false
url.kind_of?(URI::HTTP) || url.kind_of?(URI::HTTPS)
end
end
describe UrlValidator do
before do
@validator = UrlValidator.new attributes: {}
end
context 'invalid input' do
it 'should return false for a poorly formed URL' do
@validator.url_valid?('something.com').should be_false
end
it 'should return false for garbage input' do
pi = 3.14159265
@validator.url_valid?(pi).should be_false
end
it 'should return false for URLs without an HTTP protocol' do
@validator.url_valid?('ftp://secret-file-stash.net').should be_false
end
end
context 'valid input' do
it 'should return true for a correctly formed HTTP URL' do
@validator.url_valid?('http://nooooooooooooooo.com').should be_true
end
it 'should return true for a correctly formed HTTPS URL' do
@validator.url_valid?('https://google.com').should be_true
end
end
end
@abhishek77in
Copy link

Trying to run with Rails 4 as is, test fails with -

UrlValidator
  invalid input
    should return false for a poorly formed URL (FAILED - 1)

Failures:

  1) UrlValidator invalid input should return false for a poorly formed URL
     Failure/Error: @validator = UrlValidator.new attributes: {}
     ArgumentError:
       :attributes cannot be blank
     # ./spec/models/url_validator_spec.rb:4:in `new'
     # ./spec/models/url_validator_spec.rb:4:in `block (2 levels) in <top (required)>'
     # -e:1:in `<main>'

Fix -

  before do
    @validator = UrlValidator.new attributes: { url: '' }
  end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment