validates_length_of的自定义错误消息:最大值和:ruby on rails上的最小值

时间:2014-11-18 17:01:07

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

我想编写一个自定义错误消息:minimum和other for: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" 

2 个答案:

答案 0 :(得分:4)

新的表示法是:

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类型方法留在那里用于遗留支持,但在新代码中应该避免使用。

答案 1 :(得分:2)

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