Search code examples
ruby-on-railsruby-on-rails-3.2isbn

How do I use rails validates for length to check for one value or another, not a range?


I am trying to write a model for books in my rails app and I want to validate the isbn attribute but there are two possible lengths for an ISBN: 10 and 13. How do I use validates to make sure that the given isbn is either 10 OR 13 numbers long?

I thought about using a range:

validates :isbn, length: { minimum: 10, maximum: 13 }

but if it is somehow 11 or 12 numbers it { should_not be_valid }.

Is there a way to do this?


Solution

  • You can use a custom validator for that purpose:

    class Book < ActiveRecord::Base
      attr_accessible :isbn
    
      validate :check_length
    
      def check_length
        unless isbn.size == 10 or isbn.size == 13
          errors.add(:isbn, "length must be 10 or 13") 
        end
      end
    end