Class: IbanValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/validators/iban_validator.rb

Overview

Check if this is a valid IBAN number; we use the iban_tools gem for this.

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/validators/iban_validator.rb', line 3

def validate_each record, attribute, value
  begin
    require 'iban-tools'
  rescue LoadError
    raise LoadError, 'The iban-tools gem is not installed. You need to add it to your Gemfile in order to use this validation'
  end

  return if value.blank?

  errors = IBANTools::IBAN.new(value).validation_errors
  return if errors.blank?

  if options[:message]
    record.errors.add attribute, options[:message]
  elsif options[:detailed_errors]
    errors.each { |e| record.errors.add attribute, I18n.t("rails_validations.iban.#{e}") }
  else
    record.errors.add attribute, I18n.t("rails_validations.iban.invalid")
  end
end