Skip to content

Instantly share code, notes, and snippets.

@bluemont
Created June 25, 2012 04:27
Show Gist options
  • Star 26 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save bluemont/2986523 to your computer and use it in GitHub Desktop.
Save bluemont/2986523 to your computer and use it in GitHub Desktop.
ActiveModel URL Validator
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
@keilmillerjr
Copy link

Thank you. It works perfectly. :)

@keilmillerjr
Copy link

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.

@mopx
Copy link

mopx commented Oct 23, 2012

@keilmillerjr just add :allow_blank => true

@mdoliwa
Copy link

mdoliwa commented Nov 19, 2012

Thanks, that's what I was looking for.

@knzconnor
Copy link

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

@toobulkeh
Copy link

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

@johnjohndoe
Copy link

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.

@adamico
Copy link

adamico commented Nov 14, 2014

see https://gist.github.com/adamico/2a781d6a4fc2ff577e7f for a Rails 4 with I18n messages and updated and simplified specs

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