Skip to content

Instantly share code, notes, and snippets.

@Sohair63
Created January 24, 2018 12:39
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 Sohair63/5ca3b59e03c89e0a98b47b2677325840 to your computer and use it in GitHub Desktop.
Save Sohair63/5ca3b59e03c89e0a98b47b2677325840 to your computer and use it in GitHub Desktop.
ActiveModel HttpUrlValidator
# frozen_string_literal: true
module Validators
class HttpUrlValidator < ActiveModel::EachValidator
GENERIC_URI_FORMAT = /^((ftp|http|https):\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/ix
def validate_each(record, attribute, value)
uri = parse_uri(value)
record.errors.add(attribute, :bad_uri, options) unless uri
end
private
def parse_uri(value)
return unless value
uri = URI.parse(value)
# Works for both http and https
if uri.kind_of?(URI::HTTP)
uri.scheme && uri.host && uri
elsif uri.kind_of?(URI::Generic)
uri.path.match(GENERIC_URI_FORMAT)
end
rescue URI::InvalidURIError, URI::InvalidURIError, TypeError
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment