Skip to content

Instantly share code, notes, and snippets.

@virolea
Last active February 16, 2023 17:01
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save virolea/51817cf73a6f99ccf11e3cd577a28ad4 to your computer and use it in GitHub Desktop.
Save virolea/51817cf73a6f99ccf11e3cd577a28ad4 to your computer and use it in GitHub Desktop.
Rails Custom URL validator
# 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