Skip to content

Instantly share code, notes, and snippets.

@zporter
Created June 18, 2014 20:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zporter/913b983ba56155115e81 to your computer and use it in GitHub Desktop.
Save zporter/913b983ba56155115e81 to your computer and use it in GitHub Desktop.
Rails: Full URL validator
class FullUrlValidator < ActiveModel::EachValidator
VALID_SCHEMES = %w(http https)
def validate_each(record, attribute, value)
unless valid_full_url?(value)
record.errors[attribute] << (options[:message] || 'is not a valid URL')
end
end
private
def valid_full_url?(url)
url = URI.parse(url)
url.scheme.in?(VALID_SCHEMES) && url.host
rescue URI::InvalidURIError
false
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment