Sha256: 819676248b343acc0df2ac447d9e548b6609ed3eebe39cd56fe4e58f2a79af2d

Contents?: true

Size: 729 Bytes

Versions: 1

Compression:

Stored size: 729 Bytes

Contents

class UrlFormatValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    format_value(value)
    unless URI.parse(value).kind_of?(URI::HTTP) && value =~ url_regexp
      record.errors[attribute] << (options[:message] || "is invalid")
    end
  rescue URI::InvalidURIError
    record.errors[attribute] << (options[:message] || "is invalid")
  end

  def format_value(value)
    value = "http://#{value}" unless value =~ /\Ahttps?:\/\//
  end

  # Thanks to Dean Perry and Ryan Bates 
  # https://github.com/deanperry/url_formatter/blob/master/lib/url_formatter.rb
  def url_regexp
    /\Ahttps?:\/\/([\A\s:@]+:[\A\s:@]*@)?[-[[:alnum:]]]+(\.[-[[:alnum:]]]+)+\.?(:\d{1,5})?([\/?]\S*)?\z/iux
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
url_format-0.0.5 lib/url_format/url_format_validator.rb