class PortugueseValidators::PortugueseBiValidator

Validates Portuguese BI’s.

A Portuguese BI number is comprised by eight digits. Between that number and the “issue” box, the card also has a small box with a single digit. That’s the control digit. In order to validate a Portuguese BI you have to give the full number (including the control digit).

Constants

BLACKLIST

Public Instance Methods

is_valid?(number) click to toggle source

Returns true if the number is a valid BI or false otherwise.

# File lib/portuguese_validators/bi.rb, line 16
def is_valid?(number)
  return false unless number

  number = number.to_s
  looks_like_bi?(number) && valid_bi?(number)
end

Private Instance Methods

looks_like_bi?(number) click to toggle source
# File lib/portuguese_validators/bi.rb, line 37
def looks_like_bi?(number)
  return false if !number || BLACKLIST.include?(number)

  number.match(/^\d{9}$/) ? true : false
end
valid_bi?(number) click to toggle source
# File lib/portuguese_validators/bi.rb, line 25
def valid_bi?(number)
  control = number.split('').map { |digit| digit.to_i }

  sum = 0
  9.downto(2) { |num| sum += num * control.shift }

  expected = 11 - sum % 11;
  expected = 0 if expected > 9 # when the value is greater than 9 then we assume 0

  expected == control.last
end