Last active
February 16, 2023 17:01
-
-
Save virolea/51817cf73a6f99ccf11e3cd577a28ad4 to your computer and use it in GitHub Desktop.
Rails Custom URL validator
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
# Use this validator like this | |
# | |
# class User < ApplicationRecord | |
# validates :profile_link, url: true | |
# end | |
class UrlValidator < ActiveModel::EachValidator | |
def validate_each(record, attribute, value) | |
unless valid_url?(value) | |
record.errors.add(attribute, :invalid_url) | |
end | |
end | |
private | |
def valid_url?(url) | |
uri = URI.parse(url) | |
uri.is_a?(URI::HTTP) && !uri.host.nil? | |
rescue URI::InvalidURIError | |
false | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment