How to use rails to check the length to check a particular value, not a range?

I am trying to write a model for books in my rails application and I want to check the isbn attribute, but there are two possible lengths for ISBN: 10 and 13. How can I use checks to make sure that isbn is either longer than 10 OR 13?

I was thinking about using range:

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

but if it's somehow 11 or 12 numbers, this is {should_not be_valid}.

Is there any way to do this?

+4
source share
2 answers

For this purpose you can use a special validator:

 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 
+4
source

You will need to create a new method to check one length or another.

To use validation:

 validate :isbn_length 

to determine this check

 def isbn_length if isbn.length !== 10 || 13 errors.add(:isbn, "ISBN should be 10 or 13 characters long") end end 
0
source

All Articles