Class: UrlFormatValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
app/validators/url_format_validator.rb

Overview

Validate fields to look like URLs

A blank URL is considered valid (use presence validator to check for that)

Examples

validates :url, url_format: true                 # optional
validates :url, url_format: true, presence: true # required

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attr_name, value) ⇒ Object



9
10
11
12
13
14
15
16
17
18
# File 'app/validators/url_format_validator.rb', line 9

def validate_each(record, attr_name, value)
  return if value.blank?

  valid = begin
    URI.parse(value).kind_of?(URI::HTTP)
  rescue URI::InvalidURIError
    false
  end
  record.errors.add(attr_name, :url_format, options) unless valid
end