HUSTEN
HUSTEN

Reputation: 5197

How can I code if I want the same error messages on all the validation?

How can I code if I want the same error messages on all the validation?

I have 3 criterias such as presence, uniqueness and length.
I want the same error message.
But my code works only when it matched with length error.
How can I apply to all(other two)?

validates :title,   
    :presence => true,   
    :uniqueness => true,   
    :length => { :maximum => 100, :message => "Must be unique, and has to be less than 100 characters"}

Upvotes: 0

Views: 42

Answers (2)

shweta
shweta

Reputation: 8169

it can be done with validates

validates :title, 
      :presence => {:message => "Must be unique, and has to be less than 100 characters" },
      :uniqueness => {:message => "Must be unique, and has to be less than 100 characters"},
      :length => { :maximum => 100, :message => "Must be unique, and has to be less than 100 characters"}

Upvotes: 1

MrTheWalrus
MrTheWalrus

Reputation: 9700

I'm confident that there is a way to do this using validates, but if I had this problem, I'd probably just write a custom validation:

validate :title_format

def title_format
  if title.blank? || title.length > 100 || Post.where(:title => title).exists? 
    errors.add(:title, "Must be unique and less than 100 characters")
  end
end

(Replace Post with your actual model name, naturally.)

Incidentally, your message says 'less than 100 characters', but you're actually validating 'less than or equal to 100 characters'. You'll probably want to pick one or the other and be consistent about it.

Upvotes: 1

Related Questions