Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
@rietta

This comment has been minimized.

Copy link
Owner Author

@rietta rietta commented Jul 20, 2017

This is an oldie from my personal snippet collection. I really should start a gem for this.

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