Ruby on Railsで口座振替用のフォームを作成しています。
フォームを設定し、基本的な検証を設定して、すべてのフィールドが入力されていることを確認しました。
次に、IBAN (国際銀行口座番号) 番号が有効な IBAN であることを確認するための検証を設定します。
これには、文字列を操作し、それを数値に変更し、いくつかの計算を実行するいくつかの手順が含まれます。これらすべての方法を記述しました。
私の問題は、IBAN をメソッドに渡して検証を行うことができないように見えることです。
私の検証:
class DirectDebit < ActiveRecord::Base
attr_accessible :address, :amount, :bank_branch, :bic, :date_for_payment, :email, :iban, :name, :name_of_account, :phone
validates :address, :bank_branch, :bic, :date_for_payment, :email, :name, :name_of_account, :phone, presence: true
validates :amount, numericality: {greater_than_or_equal_to: 0.01}
validate :iban
def iban
## Converts all letters in 'number' to uppercase and removes any spaces and anything else that isn't a letter, number or underscore
iban = iban.upcase.scan(/\w/).join
## removes any underscores as ".scan(/\w/)" above reads in letters digits and underscores.
iban = iban.gsub(/_/, '')
## Calculates the length of 'number'
iban_length = iban.length
## Saves the first two letters in 'number' as 'country'
country = iban.scan(/\A../).join
## Checks if the length is correct for the country
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 "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
## Identifies what the first 4 characters are, and removes them from the rest of the number
first_four_characters = iban.slice!(0..3)
## Adds the first four characters to the end of the rest
reordered_number = iban + first_four_characters
## Set up an array and have each character in the reordered number read into it, changing it to the appropriate number if it is a letter.
letters_removed = []
reordered_number.scan(/./) do |character|
case character
when "A"
letters_removed << 10
...
when "9"
letters_removed <<9
end
end
## Change the array to a String and then to a number
letters_removed = letters_removed.join.to_i
## Check to see if it gives a remainder of one when divided by 97
remainder = letters_removed % 97
## Output that it is a valid number if the remainder when it is divided by 97 is 1 and if it is the correct length for the country.
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 is: " + special)
end
end
end