我正在嘗試與任何國家/地區iban代碼一起執行iban驗證。我從構建代碼的stackoverflow獲得了一些幫助,但仍然存在一些問題,我不知道它在哪裏。Ruby on Rails模型文件中的IBAN驗證
總是我得到'這不是有效的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
它應該是'驗證:valid_iban'和'驗證:iban,presence:true'兩個獨立的驗證,你應該傳遞一個方法來驗證。 – Surya 2014-10-09 09:27:50
我剛剛做到了。但問題是一樣的。我認爲它在驗證碼 – 2014-10-09 09:37:42
因此,您的條件:'餘額== 1 && length_correct_for_country'總是被評估爲false,然後檢查您的邏輯是否正確。 – Surya 2014-10-09 09:41:30