Class: UrlValidator

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

Overview

The majority of the Supplejack API code is Crown copyright © 2014, New Zealand Government, and is licensed under the GNU General Public License, version 3. One component is a third party component. See github.com/DigitalNZ/supplejack_api for details.

Supplejack was created by DigitalNZ at the National Library of NZ and the Department of Internal Affairs. digitalnz.org/supplejack

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/url_validator.rb', line 10

def validate_each(record, attribute, value)
  valid = false

  return nil unless value.present?

  if value.is_a?(Array)
    value.each do |v|
      valid = validate_url(v)
      break unless valid
    end
  else
    valid = validate_url(value)
  end

  unless valid
    record.errors[attribute] << (options[:message] || 'is not an url')
  end
end

#validate_url(value) ⇒ Object



29
30
31
32
33
34
35
36
37
# File 'lib/url_validator.rb', line 29

def validate_url(value)
  protocol = '(http|https)'
  host = '[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?'
  ip_host = '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
  port = '(:\d{1,5})?'

  regex = %r{ ^#{protocol}:\/\/((#{host})|(#{ip_host}))#{port}\/.*)?$ }ix
  !!value.match(regex)
end