Sha256: d3235d6d6dbbf00912a980ce06bc1d9f738a3f9a9af3ab7fb5c7bd459359d517

Contents?: true

Size: 691 Bytes

Versions: 4

Compression:

Stored size: 691 Bytes

Contents

class IsbnValidator < ActiveModel::EachValidator

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

  private

  def valid_format?(value)
    value = ''.freeze if value.blank?
    value = value.gsub(/-| /, ''.freeze).downcase.chars

    [10, 13].freeze.include?(value.size) &&
    value.all? { |c| ['0', '1', '2' , '3', '4', '5', '6', '7', '8', '9', '0', 'x'].freeze.include?(c) }
  end

  def valid_length?(value)
    value.present?
  end

  def valid?(value)
    valid_length?(value) &&
    valid_format?(value)
  end

end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
active_validation-2.6.0 lib/active_validation/validators/isbn_validator.rb
active_validation-2.5.0 lib/active_validation/validators/isbn_validator.rb
active_validation-2.4.0 lib/active_validation/validators/isbn_validator.rb
active_validation-2.3.0 lib/active_validation/validators/isbn_validator.rb