【问题标题】:custom error message for validates_length_of :maximum and :minimum on ruby on railsvalidates_length_of 的自定义错误消息:maximum 和 :minimum on ruby​​ on rails
【发布时间】:2014-11-18 17:01:06
【问题描述】:

我想为 :minimum 编写自定义错误消息,而为 :maximum 编写其他错误消息

我有以下代码行

validates_length_of :user_name, :minimum=>5,:maximum=>30

  ej if the length of :user_name is < 5 "The user_name must to have 5 characters as minimum"
  ej if the length of :user_name is > 30 "The user_name must to have 30 characters as maximum" 

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4


    【解决方案1】:

    更新的符号是:

    validates :user_name,
      length: { 
        minimum: 5,
        maximum: 30,
        too_short: "The user name must have at least %{count} characters.",
        too_long: "The user name must have no more than %{count} characters."
      }
    

    the documentation 中列出了更多示例。

    旧的validates_length_of 类型方法保留在那里以供遗留支持,但在新代码中应该避免使用。

    【讨论】:

      【解决方案2】:

      也许像
      validates_length_of :user_name, :minimum =&gt;5,:maximum=&gt;30, :too_short =&gt; 'is too short', :too_long =&gt; 'is too long'

      【讨论】:

      • 但是如何删除messege中模型字段的名称。我写了这段代码: validates_length_of :subject, :maximum => 255, :too_long => 'checklist item is too long' 但我现在的实际信息是:“Subject checklist item is too long”
      猜你喜欢
      • 2014-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-11
      • 2016-09-08
      相关资源
      最近更新 更多