Module: ActiveModel::Validations::ClassMethods

Defined in:
lib/url_validator.rb

Instance Method Summary collapse

Instance Method Details

#validates_url(*attr_names) ⇒ Object

Validates whether the value of the specified attribute is valid url.

class User
  include ActiveModel::Validations
  attr_accessor :website, :ftpsite
  validates_url :website, :allow_blank => true
  validates_url :ftpsite, :schemes => ['ftp']
end

Configuration options:

  • :message - A custom error message (default is: “is not a valid URL”).

  • :allow_nil - If set to true, skips this validation if the attribute is nil (default is false).

  • :allow_blank - If set to true, skips this validation if the attribute is blank (default is false).

  • :schemes - Array of URI schemes to validate against. (default is [‘http’, ‘https’])



59
60
61
62
63
64
65
66
67
68
69
# File 'lib/url_validator.rb', line 59

def validates_url(*attr_names)
  attrs = attr_names.take_while{|a| !a.instance_of?(Hash)}
  attrs.each do |a_name|
    class_eval <<-EOF
      def #{a_name}_normalized
        Addressable::IDNA.to_ascii(#{a_name}.to_s)
      end
    EOF
  end
  validates_with UrlValidator, _merge_attributes(attr_names)
end