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