Created
July 20, 2017 13:56
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 is an oldie from my personal snippet collection. I really should start a gem for this.