向自定义验证器添加错误消息 [英] Adding an error message to a custom validator

查看:104
本文介绍了向自定义验证器添加错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义验证器,当它失败但无法执行时,我试图输出一条错误消息。

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

我有如下:

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

但是收到错误

Unknown validator: 'MessageValidator'

当我尝试放入验证程序末尾的消息,用逗号分隔has_association?变成了问号,并变成了橙色

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

推荐答案

消息 if 参数应放在状态的散列中:

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

如果您尝试以这种方式向其中添加一条消息,或者如果条件,Rails将不知道要将消息/条件应用于哪个验证。因此,您需要设置每个验证的消息:

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"}

这篇关于向自定义验证器添加错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆