small medium large xlarge

 

Pt-B-2

Eric Ricketts says:

I decided to make a custom error message within the validates method:

validates :title, length: {minimum: 10, too_short: "10 character minimum"} Looking at the Rail documentation for validations: Rails Guides for length validations, I found too_short: to be a valid option for the length validation.

I added the following line to my test for product.title length validations in product_test.rb

assert_equal ["10 character minimum"], product.errors[:title]

The rest of my test code is in my prior post related to Chapter 7, Pt-B-1.

To solve the length validation try starting with writing the test first.

product = Product.new(:title => “too tiny”, :description => “this product has a title that is toooooo tiny”, :price => 0.5, :image_url => “tiny.gif”)

To customize error messages, you’ll want to change the translations. You can add customized translations in config/locales/en.yml for example. See Translating ActiveRecord for more info.

Dorian says:

Looking in the docs, I couldn’t find any way to customise the message when using the short form ‘validates’, so I switched to the long form ‘validates_uniqueness_of’:

validates_uniqueness_of :title, :message => “must be unique”

Eric says:

The API documentation states “This method (validates) is a shortcut to all default validators and any custom validator classes ending in ‘Validator’. “

validates :title, :length => {:minimum => 10, :too_short => “is too short and must contain at least 10 characters”}

Phill says:

I was able to customize the message using the short form by using the following: validates :title, uniqueness: {message: 'must be unique. Show some originality!'}

Alex says:

I am able to use this one: validates :title, :description, :image_url, presence: { message: "can't be empty" }
Page History
  • V14: Eric Ricketts [9 months ago]
  • V13: Eric Ricketts [9 months ago]
  • V12: Eric Ricketts [9 months ago]
  • V11: Eric Ricketts [9 months ago]
  • V11: Alex Emelyanov [about 3 years ago]
  • V10: Alex Emelyanov [about 3 years ago]
  • V9: Alex Emelyanov [about 3 years ago]
  • V8: Alex Emelyanov [about 3 years ago]
  • V7: Phillip J Ramey [over 4 years ago]
  • V6: Eric Treece [over 5 years ago]