Create a folder app/validators. Add this to it. Now you can do "validate :some_field, url: true" in your model validations. Works in Rails 3, 4, and 5.
class UrlValidator < ActiveModel::EachValidator | |
def validate_each(record, attribute, value) | |
valid = begin | |
URI.parse(value.to_s).kind_of?(URI::HTTP) | |
rescue URI::InvalidURIError | |
false | |
end | |
unless valid | |
record.errors[attribute] << (options[:message] || "is an invalid URL") | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
This is an oldie from my personal snippet collection. I really should start a gem for this.