Class: PhoneValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Includes:
Phonelib::Core
Defined in:
lib/validators/phone_validator.rb

Overview

Validator class for phone validations

Examples

Validates that attribute is a valid phone number. If empty value passed for attribute it fails.

class Phone < ActiveRecord::Base
  attr_accessible :number
  validates :number, phone: true
end

Validates that attribute is a possible phone number. If empty value passed for attribute it fails.

class Phone < ActiveRecord::Base
  attr_accessible :number
  validates :number, phone: { possible: true }
end

Validates that attribute is a valid phone number. Empty value is allowed to be passed.

class Phone < ActiveRecord::Base
  attr_accessible :number
  validates :number, phone: { allow_blank: true }
end

Constant Summary

Constants included from Phonelib::Core

Phonelib::Core::COUNTRY_CODE, Phonelib::Core::DEFAULT_NUMBER_FORMAT, Phonelib::Core::FIXED_LINE, Phonelib::Core::FIXED_OR_MOBILE, Phonelib::Core::GENERAL, Phonelib::Core::MOBILE, Phonelib::Core::NATIONAL_PREFIX, Phonelib::Core::NATIONAL_PREFIX_RULE, Phonelib::Core::NOT_FOR_CHECK, Phonelib::Core::PAGER, Phonelib::Core::PERSONAL_NUMBER, Phonelib::Core::POSSIBLE_PATTERN, Phonelib::Core::PREMIUM_RATE, Phonelib::Core::SHARED_COST, Phonelib::Core::TOLL_FREE, Phonelib::Core::TYPES, Phonelib::Core::UAN, Phonelib::Core::VALID_PATTERN, Phonelib::Core::VOICEMAIL, Phonelib::Core::VOIP

Instance Method Summary collapse

Methods included from Phonelib::Core

#default_country, #default_country=, #impossible?, #invalid?, #invalid_for_country?, #parse, #possible?, #valid?, #valid_for_country?

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object

Validation method



33
34
35
36
37
38
39
# File 'lib/validators/phone_validator.rb', line 33

def validate_each(record, attribute, value)
  phone = parse(value)
  valid = options[:possible] ? phone.possible? : phone.valid?
  valid = true if options[:allow_blank] && phone.original.blank?

  record.errors.add(attribute, options[:message] || :invalid) unless valid
end