Class: UrlValidator

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

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.validate(value) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'app/validators/url_validator.rb', line 8

def self.validate(value)
  schemes = ['https', 'http']

  begin
    uri = URI.parse(value)
    host = uri && uri.host
    scheme = uri && uri.scheme

    valid_scheme = host && scheme && schemes.include?(scheme)
    valid_raw_url = scheme && value.match?(URI.regexp([scheme]))

    return false unless valid_raw_url && valid_scheme
  rescue URI::InvalidURIError
    return false
  end

  true
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



2
3
4
5
6
# File 'app/validators/url_validator.rb', line 2

def validate_each(record, attribute, value)
  if !self.class.validate(value)
    record.errors.add(attribute, :invalid)
  end
end