Class: ActiveModelValidators::UrlValidator
- Inherits:
-
ActiveModel::EachValidator
- Object
- ActiveModel::EachValidator
- ActiveModelValidators::UrlValidator
- Defined in:
- lib/active_model_validators/url_validator.rb
Overview
URL validator
Constant Summary collapse
- DEFAULT_PROTOCOLS =
Default protocols used for validation if no custom protocols provided
DEFAULT_PROTOCOLS = [::URI::HTTP, ::URI::HTTPS] [::URI::HTTP, ::URI::HTTPS].freeze
Instance Method Summary collapse
-
#validate_each(record, attribute, value) ⇒ Object
Adds error if there is invalid URL address.
Instance Method Details
#validate_each(record, attribute, value) ⇒ Object
Adds error if there is invalid URL address.
By default it works with http and https.
It can be easily extended with protocols param
-
record- ActiveRecord model -
attr- model attribute to store an URL -
value- value, supposed to be a valid URL-adress
Example
class MyModel < ActiveRecord::Base
# default usage
validates :my_url, :'active_model_validators/url' => true
end
class MyModel < ActiveRecord::Base
# with custom URL protocols
validates :my_url, :'active_model_validators/url' => { protocols: [URI::HTTP, URI::HTTPS, URI::FTP] }
end
valid_url = 'https://www.valid.com'
my_model_instance = MyModel.create(my_url: valid_url)
my_model_instance.valid? # => true
my_model_instance.my_attribute = 'invalid_url'
my_model_instance.valid? # => false
38 39 40 |
# File 'lib/active_model_validators/url_validator.rb', line 38 def validate_each(record, attribute, value) record.errors.add(attribute, ) unless url_valid?(value) end |