문제

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?

도움이 되었습니까?

해결책

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

다른 팁

You would need to create a new method to validate one length OR another.

for validation use:

validate :isbn_length

to define this validation

def isbn_length
  if isbn.length !== 10 || 13
    errors.add(:isbn, "ISBN should be 10 or 13 characters long")
  end
end
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top