Sha256: d7d8530f82f79941ef33fc0f3974d24bbb57859e6e66bfa1e02ff43f1ac80050

Contents?: true

Size: 715 Bytes

Versions: 1

Compression:

Stored size: 715 Bytes

Contents

class IsbnValidator < ActiveModel::EachValidator

  def validate_each(record, attribute, value)
    unless valid?(value.to_s, options)
      record.errors[attribute] << (options[:message] || I18n.t('errors.messages.isbn'))
    end
  end

  private

  def valid_format?(isbn)
    ['0','1','2','3','4','5','6','7','8','9','0','x'].include?(isbn)
  end

  def self.validate_format(isbn)
    isbn = '' if isbn.nil?
    isbn.gsub!(/-| /, '')
    isbn.downcase!

    if isbn.size == 10 || isbn.size == 13
      isbn.chars.all? { |char| ['0','1','2','3','4','5','6','7','8','9','0','x'].include?(char) }
    else
      return false
    end
  end

  def valid?(isbn, options)
    self.class.validate_format(isbn)
  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
flash_validators-1.1.0 lib/flash_validators/validators/isbn_validator.rb