我正在尝试对任何国家的iban代码进行iban验证我从stackoverflow那里得到了一些构建代码的帮助,但是我仍然有一些问题,我不知道它在哪里。
我总是收到“这不是有效的IBAN”错误消息但有时我会尝试将IBAN代码定义为正确的国家。
在代码中有人帮我做这个验证吗?
代码在这里:
class BankAccount < ActiveRecord::Base
belongs_to :user
validates :bank_name, presence: true
validate :iban, :valid_iban?, presence: true
private
def valid_iban?
ibans = iban.upcase.scan(/\w/).join
ibans = ibans.gsub(/_/, '')
iban_length = ibans.length
country = ibans.scan(/\A../).join
length_correct_for_country = true
case country
when "IE"
if iban_length == 22
length_correct_for_country = true
else
length_correct_for_country = false
end
when "AL"
if iban_length == 28
length_correct_for_country = true
else
length_correct_for_country = false
end
when "TR"
if iban_length == 26
length_correct_for_country = true
else
length_correct_for_country = false
end
when "GB"
if iban_length == 22
length_correct_for_country = true
else
length_correct_for_country = false
end
when "VG"
if iban_length == 24
length_correct_for_country = true
else
length_correct_for_country = false
end
end
first_four_characters = ibans.slice!(0..3)
reordered_number = ibans + first_four_characters
letters_removed = []
reordered_number.scan(/./) do |character|
case character
when "A"
letters_removed << 10
when "9"
letters_removed <<9
end
end
letters_removed = letters_removed.join.to_i
remainder = letters_removed % 97
if remainder == 1 && length_correct_for_country
else
remainder = remainder.to_s
errors.add(:iban, " That is not a valid IBAN. The IBAN that is being supplied")
end
end
end
最佳答案
iban-toolsgem可用于此目的,它工作得非常好。
为了在Rails中使用gem,我建议编写一个验证器类。
先把这个放进你的Gemfile
:
gem 'iban-tools'
然后运行
bundle
。然后创建一个新目录
app/validators
并在其中创建一个名为iban_validator.rb
的文件,其中包含以下内容:require 'iban-tools'
class IbanValidator < ActiveModel::Validator
def validate(record)
unless IBANTools::IBAN.valid?(record.iban)
record.errors.add :iban, record.errors.generate_message(:iban, :invalid)
end
end
end
在你的模特课上写下:
validates_with IbanValidator