Adding an error message to a custom validator
Asked Answered
C

1

9

I have a custom validator and I am trying to output an error message when it fails but have been unable to do so. Could someone please tell me if I am doing this in the correct place.

class User < ActiveRecord::Base
  self.table_name = "user"

  attr_accessible :name, :ip, :printer_port, :scanner_port

  validates :name,        :presence => true,
                          :length => { :maximum => 75 },
                          :uniqueness => true                          

  validates :ip,          :length => { :maximum => 75 },
                          :allow_nil => true     

  validates :printer_port, :presence => true, :if => :has_association? 

  validates :scanner_port, :presence => true, :if => :has_association?          

  def has_association?
    ip != nil
  end
end

I had it as follows:

validates :printer_port, :presence => true, :message => "can't be blank", :if => :has_wfm_association?

But was receiving an error

Unknown validator: 'MessageValidator'

And when I tried to put the message at the end of the validator the comma seperating the has_association? turned the question mark and comma orange

Catbird answered 26/4, 2012 at 14:23 Comment(0)
F
18

The message and if parameters should be inside a hash for presence:

validates :printer_port, :presence => {:message => "can't be blank", :if => :has_wfm_association?}

This is because you can load multiple validations in a single line:

validates :foo, :presence => true, :uniqueness => true

If you tried to add a message to that the way you did, or an if condition, Rails wouldn't know what validation to apply the message/conditional to. So instead, you need to set the message per-validation:

validates :foo, :presence => {:message => "must be present"},
                :uniqueness => {:message => "must be unique"}
Froufrou answered 26/4, 2012 at 14:46 Comment(2)
Do I not need to include the true statement in presence? When I do this the ? and the end of the hash are running together and both turning orange.Catbird
Just needed to put the space, thanks for your help Dylan very much appreciated :)Catbird

© 2022 - 2024 — McMap. All rights reserved.