Class: Israeli::Validators::PostalCode

Inherits:
Object
  • Object
show all
Defined in:
lib/israeli/validators/postal_code.rb

Overview

Validates Israeli postal codes (Mikud).

Israeli postal codes consist of exactly 7 digits. They are organized geographically from north to south, with the first 2 digits indicating the postal area. Jerusalem postal codes start with 9 despite its central location.

Examples:

Basic validation

Israeli::Validators::PostalCode.valid?("2610101") # => true
Israeli::Validators::PostalCode.valid?("26101 01") # => true (with space)

Regional examples

Israeli::Validators::PostalCode.valid?("1029200") # => true (Metula, north)
Israeli::Validators::PostalCode.valid?("8800000") # => true (Eilat, south)
Israeli::Validators::PostalCode.valid?("9100000") # => true (Jerusalem)

See Also:

Class Method Summary collapse

Class Method Details

.format(value, style: :compact) ⇒ String?

Formats a postal code to standard representation.

Examples:

Israeli::Validators::PostalCode.format("26101 01")             # => "2610101"
Israeli::Validators::PostalCode.format("2610101", style: :spaced) # => "26101 01"

Parameters:

  • value (String, nil)

    The postal code to format

  • style (Symbol) (defaults to: :compact)

    :compact (7 digits) or :spaced (5+2 format)

Returns:

  • (String, nil)

    Formatted postal code, or nil if invalid



62
63
64
65
66
67
68
69
70
# File 'lib/israeli/validators/postal_code.rb', line 62

def self.format(value, style: :compact)
  digits = Sanitizer.digits_only(value)
  return nil unless valid?(digits)

  case style
  when :spaced then "#{digits[0..4]} #{digits[5..6]}"
  else digits
  end
end

.invalid_reason(value) ⇒ Symbol?

Returns the reason why a postal code is invalid.

Examples:

Israeli::Validators::PostalCode.invalid_reason("123")     # => :wrong_length
Israeli::Validators::PostalCode.invalid_reason("")        # => :blank
Israeli::Validators::PostalCode.invalid_reason("2610101") # => nil (valid)

Parameters:

  • value (String, nil)

    The postal code to check

Returns:

  • (Symbol, nil)

    Reason code or nil if valid

    • :blank - Input is nil or empty

    • :wrong_length - Not exactly 7 digits



45
46
47
48
49
50
51
# File 'lib/israeli/validators/postal_code.rb', line 45

def self.invalid_reason(value)
  digits = Sanitizer.digits_only(value)
  return :blank if digits.nil? || digits.empty?
  return :wrong_length unless digits.match?(/\A\d{7}\z/)

  nil
end

.valid?(value) ⇒ Boolean

Validates an Israeli postal code.

Parameters:

  • value (String, nil)

    The postal code to validate

Returns:

  • (Boolean)

    true if valid 7-digit format, false otherwise



27
28
29
30
31
32
# File 'lib/israeli/validators/postal_code.rb', line 27

def self.valid?(value)
  digits = Sanitizer.digits_only(value)
  return false if digits.nil?

  digits.match?(/\A\d{7}\z/)
end