Class: IsraeliPhoneValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/israeli/active_model/israeli_phone_validator.rb

Overview

Validates that an attribute is a valid Israeli phone number.

Examples:

Basic usage (accepts mobile, landline, or VoIP)

class Contact < ApplicationRecord
  validates :phone, israeli_phone: true
end

Mobile only

class Contact < ApplicationRecord
  validates :mobile_phone, israeli_phone: { type: :mobile }
end

Landline only

class Contact < ApplicationRecord
  validates :office_phone, israeli_phone: { type: :landline }
end

VoIP only

class Contact < ApplicationRecord
  validates :voip_number, israeli_phone: { type: :voip }
end

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/israeli/active_model/israeli_phone_validator.rb', line 27

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

  phone_type = options[:type] || :any
  return if Israeli::Validators::Phone.valid?(value, type: phone_type)

  reason = Israeli::Validators::Phone.invalid_reason(value, type: phone_type)
  detected_type = Israeli::Validators::Phone.detect_type(value)
  record.errors.add(
    attribute,
    options[:message] || :invalid,
    reason: reason,
    expected_type: phone_type,
    detected_type: detected_type
  )
end