Class: UrlFormatValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/url_format/url_format_validator.rb

Instance Method Summary collapse

Instance Method Details

#format_value(value) ⇒ Object



11
12
13
# File 'lib/url_format/url_format_validator.rb', line 11

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

#url_regexpObject



17
18
19
# File 'lib/url_format/url_format_validator.rb', line 17

def url_regexp
  /\Ahttps?:\/\/([\A\s:@]+:[\A\s:@]*@)?[-[[:alnum:]]]+(\.[-[[:alnum:]]]+)+\.?(:\d{1,5})?([\/?]\S*)?\z/iux
end

#validate_each(record, attribute, value) ⇒ Object



2
3
4
5
6
7
8
9
# File 'lib/url_format/url_format_validator.rb', line 2

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