Class: Israeli::Validators::Id

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

Overview

Validates Israeli ID numbers (Mispar Zehut / Teudat Zehut).

Israeli ID numbers are 9-digit numbers where the last digit is a check digit calculated using the Luhn algorithm (mod 10).

Examples:

Basic validation

Israeli::Validators::Id.valid?("123456782") # => true
Israeli::Validators::Id.valid?("123456789") # => false

With formatting

Israeli::Validators::Id.valid?("12345678-2") # => true
Israeli::Validators::Id.valid?("012345678")  # => true (leading zero)

See Also:

Class Method Summary collapse

Class Method Details

.format(value) ⇒ String?

Formats an Israeli ID to standard 9-digit format.

Examples:

Israeli::Validators::Id.format("12345678-2") # => "123456782"
Israeli::Validators::Id.format(12345678)     # => "012345678"

Parameters:

  • value (String, Integer, nil)

    The ID number to format

Returns:

  • (String, nil)

    9-digit formatted ID, or nil if invalid



71
72
73
74
75
76
77
78
79
# File 'lib/israeli/validators/id.rb', line 71

def self.format(value)
  digits = Sanitizer.digits_only(value)
  return nil if digits.nil? || digits.empty?

  padded = digits.rjust(9, "0")
  return nil unless padded.match?(/\A\d{9}\z/) && Luhn.valid?(padded)

  padded
end

.invalid_reason(value) ⇒ Symbol?

Returns the reason why an ID is invalid.

Examples:

Israeli::Validators::Id.invalid_reason("123456789") # => :invalid_checksum
Israeli::Validators::Id.invalid_reason("")          # => :blank
Israeli::Validators::Id.invalid_reason("123456782") # => nil (valid)

Parameters:

  • value (String, Integer, nil)

    The ID number to check

Returns:

  • (Symbol, nil)

    Reason code or nil if valid

    • :blank - Input is nil or empty
    • :wrong_length - Not 9 digits after padding
    • :invalid_checksum - Luhn checksum failed


52
53
54
55
56
57
58
59
60
61
# File 'lib/israeli/validators/id.rb', line 52

def self.invalid_reason(value)
  digits = Sanitizer.digits_only(value)
  return :blank if digits.nil? || digits.empty?

  padded = digits.rjust(9, "0")
  return :wrong_length unless padded.match?(/\A\d{9}\z/)
  return :invalid_checksum unless Luhn.valid?(padded)

  nil
end

.valid?(value) ⇒ Boolean

Validates an Israeli ID number.

Accepts formatted input (with hyphens/spaces) and handles leading zeros. IDs shorter than 9 digits are automatically left-padded with zeros.

Parameters:

  • value (String, Integer, nil)

    The ID number to validate

Returns:

  • (Boolean)

    true if valid, false otherwise



27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/israeli/validators/id.rb', line 27

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

  # Left-pad to 9 digits if shorter (handles IDs like "12345678")
  padded = digits.rjust(9, "0")

  # Must be exactly 9 digits after padding
  return false unless padded.match?(/\A\d{9}\z/)

  Luhn.valid?(padded)
end