Rails 3:验证中的自定义错误消息

时间:2010-09-20 20:14:05

标签: validation forms ruby-on-rails-3 activemodel

我不明白为什么以下在Rails 3中不起作用。我得到“未定义的局部变量或方法`custom_message'”错误。

validates :to_email, :email_format => { :message => custom_message }

def custom_message
  self.to_name + "'s email is not valid"
end

我也尝试过使用:message => :custom_message,而不是rails-validation-message-error帖子中建议的,没有运气。

:email_format是位于lib文件夹中的自定义验证器:

class EmailFormatValidator < ActiveModel::EachValidator
  def validate_each(object, attribute, value)
    unless value =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
      object.errors[attribute] << (options[:message] || 'is not valid')
    end
  end
end

3 个答案:

答案 0 :(得分:1)

如果有人有兴趣,我想出了以下问题的解决方案:

型号:

validates :to_email, :email_format => { :name_attr => :to_name, :message => "'s email is not valid" }

LIB / email_format_validator.rb:

class EmailFormatValidator < ActiveModel::EachValidator

  def validate_each(object, attribute, value)
    unless value =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i

      error_message = if options[:message] && options[:name_attr]
        object.send(options[:name_attr]).capitalize + options[:message]
      elsif options[:message]
        options[:message]
      else
        'is not valid'
      end

      object.errors[attribute] << error_message
    end
  end
end

答案 1 :(得分:1)

仅供参考,我相信这是正在进行的。 'validates'方法是一种类方法,即MyModel.validates()。当你将这些参数传递给'validates'而你调用'custom_message'时,你实际上是在调用MyModel.custom_message。所以你需要像

这样的东西
def self.custom_message
  " is not a valid email address."
end

validates :to_email, :email_format => { :message => custom_message }

在调用验证之前定义了self.custom_message。

答案 2 :(得分:0)

可能需要在验证之上定义“custom_message”方法。

相关问题