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
The validator function needs to return null if no errors were found in the field value, meaning that the value is valid.
Drivers can specify their own error types and error messages. To define a custom error message, you must first define a new IO_ERR_XXX value to specify as the ErrorCode member of the error log entry. The Event Viewer uses the IO_ERR_XXX value to look up the driver's error message.
Implementing the Validator Interface A Validator implementation must contain a constructor, a set of accessor methods for any attributes on the tag, and a validate method, which overrides the validate method of the Validator interface.
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"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With