Skip to content

Instantly share code, notes, and snippets.

@rietta
Created July 20, 2017 13:56
Show Gist options
  • Save rietta/a2648546d8039da63ed1183f7be2e40b to your computer and use it in GitHub Desktop.
Save rietta/a2648546d8039da63ed1183f7be2e40b to your computer and use it in GitHub Desktop.
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
Copy link
Author

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