Created
January 24, 2018 12:39
-
-
Save Sohair63/5ca3b59e03c89e0a98b47b2677325840 to your computer and use it in GitHub Desktop.
ActiveModel HttpUrlValidator
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
# 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