Sha256: a70d0cd0dfb70107499c8e3fca1e98db6075b1c35eb564d6cf7cb366e5151f10

Contents?: true

Size: 650 Bytes

Versions: 7

Compression:

Stored size: 650 Bytes

Contents

class IsbnValidator < ActiveModel::EachValidator

  CHARACTERS ||= %w(0 1 2 3 4 5 6 7 8 9 0 x).freeze

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

  private

  def valid_format?(value)
    return(false) if value.empty?
    value = value.gsub(/-| /, '').downcase.chars

    [10, 13].include?(value.size) && value.all? { |chr| CHARACTERS.include?(chr) }
  end

  def valid_length?(value)
    value.present?
  end

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

end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
active_validation-4.0.7 lib/active_validation/validators/isbn_validator.rb
active_validation-4.0.6 lib/active_validation/validators/isbn_validator.rb
active_validation-4.0.5 lib/active_validation/validators/isbn_validator.rb
active_validation-4.0.4 lib/active_validation/validators/isbn_validator.rb
active_validation-4.0.3 lib/active_validation/validators/isbn_validator.rb
active_validation-4.0.2 lib/active_validation/validators/isbn_validator.rb
active_validation-4.0.1 lib/active_validation/validators/isbn_validator.rb