Skip to content
Create a gist now

Instantly share code, notes, and snippets.

ActiveModel URL Validator
class UrlValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
valid = begin
rescue URI::InvalidURIError
unless valid
record.errors[attribute] << (options[:message] || "is an invalid URL")

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.

mopx commented Oct 23, 2012

@keilmillerjr just add :allow_blank => true

mdoliwa commented Nov 19, 2012

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:


.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.

adamico commented Nov 14, 2014

see 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
Something went wrong with that request. Please try again.