public
Last active

ActiveModel URL Validator

  • Download Gist
url_validator.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14
class UrlValidator < ActiveModel::EachValidator
 
def validate_each(record, attribute, value)
valid = begin
URI.parse(value).kind_of?(URI::HTTP)
rescue URI::InvalidURIError
false
end
unless valid
record.errors[attribute] << (options[:message] || "is an invalid URL")
end
end
 
end

Thank you. It works perfectly. :)

One issue I am having is that blank urls not validated by presence are still resulting in an error. I'll fork this and see if I can fix it.

@keilmillerjr just add :allow_blank => true

Thanks, that's what I was looking for.

https? unicode? I forked, and cleaned-up a bit, but it's untested - just for discussion sake: https://gist.github.com/timocratic/5113293

.kind_of?(URI::HTTP) handles HTTPS.

Benjamin Fleischer posted a modified version based on what @timocratic published. He also included an updated version of the spec. An updated fork of this Gist can be found here.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.