最近几天我正在研究ABN(澳大利亚商业号码),我试着写一个片段来验证ABN。
我很好奇89。 89为什么?为什么不是另一个号码我应该称之为数字?
class AbnValidator < ActiveModel::EachValidator
ABN_LENGTH = 11
FACTOR_WEIGHTING = [10, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19].freeze
# Reference https://abr.business.gov.au/HelpAbnFormat.aspx
def validate_each(record, attribute, value)
unless valid?(value)
record.errors[attribute] << (options[:message] || 'ABN is invalid')
end
end
private
def valid?(value)
value = value.gsub(/\s+/, '')
return false unless value.length == ABN_LENGTH
sum = 0
(0..10).each do |i|
c = value[i, 1]
digit = c.to_i - (i.zero? ? 1 : 0)
sum += FACTOR_WEIGHTING[i] * digit
end
(sum % 89).zero?
end
end
感谢您的解释!