【问题标题】:Rails 3: Custom error message in validationRails 3:验证中的自定义错误消息
【发布时间】:2010-09-20 20:14:05
【问题描述】:

我不明白为什么以下内容在 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

【问题讨论】:

  • 我可以使用您的确切代码复制您的错误,但是当我按照您的建议将其更改为 :message =&gt; :custom_message 时,错误就会消失。

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


【解决方案1】:

仅供参考,这就是我认为正在发生的事情。 'validates' 方法是一个类方法,即 MyModel.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 }

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

【讨论】:

    【解决方案2】:

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

    型号:

    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
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2011-07-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-21
        • 1970-01-01
        • 2021-12-09
        • 1970-01-01
        相关资源
        最近更新 更多