Class: PhoneValidator

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

Overview

Defined at the top level (not under PicoPhone::Rails) so ActiveModel's validator lookup resolves validates :phone, phone: { ... } to this class — EachValidator constantizes "#keykey.to_skey.to_s.camelizeValidator" against the including model's namespace up through Object, same convention the email_validator gem uses.

Examples:

validates :phone, phone: { region: "US", allow_blank: true }

Looser "possible" check instead of full validity

validates :phone, phone: { region: "US", possible: true }

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ void

This method returns an undefined value.

Parameters:

  • record (ActiveModel::Validations)
  • attribute (Symbol)
  • value (String, PicoPhone::PhoneNumber, nil)
  • options (Hash)

    a customizable set of options



23
24
25
26
27
28
29
# File 'lib/phone_validator.rb', line 23

def validate_each(record, attribute, value)
  return if options[:allow_blank] && value.blank?

  return if phone_valid?(value.to_s)

  record.errors.add(attribute, :invalid_phone, **options.slice(:message))
end