Mike Tallerico
Mike Tallerico

Reputation: 125

How to set validation up for multiple specific lengths

I am setting up some validation in my model and am curious on how to validate for 3 different specific lenghts? I want to validate 10, 12 or 13 specifically for the UPC. I see in the docs how to do it for one specifically.

class Product < ApplicationRecord
  validates :name, presence: true, length: { maximum: 1024 }, uniqueness: true
  validates :upc, presence: true, numericality: { only_integer: true }, length: { is: 10 }, uniqueness: true
  has_many :product_properties
  has_many :properties, through: :product_properties
end

Thanks for any help you can give me.

Upvotes: 1

Views: 166

Answers (1)

You'll have to write a custom method

validate :check_for_length

def check_for_length
  errors.add(:upc, :wrong_length) unless [10,12,13].include?(upc.length)
end

Now in your en.yml

en:
  activerecord:
    errors:
      models:
        product:
          attributes:
            upc:
              wrong_length: "your_message"

Upvotes: 2

Related Questions