自定义验证消息

时间:2013-10-11 13:58:01

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

我想知道如何完全自定义验证消息,这就是我的代码的样子

user_profile.rb: -

validates: first_name, :presence => {:message => "First name can't be blank"}

但这给了我一条错误消息用户个人资料名字第一个名字不能为空,我想要的是有错误信息名字不能为空。我四处寻找解决方案,我想我必须在en.yml文件中做一些更改,但我不知道该怎么做。有什么帮助吗?

2 个答案:

答案 0 :(得分:6)

您有三种选择:

validate do |user|
  user.errors.add_to_base("First name can't be blank") if user.first_name.blank?
end

执行user_profile.errors.full_messages会给你 - > ["First Name can't be blank"]

validates: first_name, :presence => {:message => "can't be blank"}

# config/locales/en.yml
en:
  activerecord:
    attributes:
      user_profile:
        first_name: "First name"
    errors:
      models:
        user_profile:
          attributes:
            first_name:
              blank: "can't be blank"

有关如何使用区域设置的更多信息,请查看this

答案 1 :(得分:0)

Rails使用自己的错误处理。这意味着它显示了数据库列。这导致列的名称 *不能为空。

尝试使用类似的东西,只需要改变你的模型。

<% if object.errors.any? %>
 <div id="error_explanation">
  <h2>
   <%= pluralize(object.errors.count, "error") %>
   probited this <%= object.class.to_s.underscore.humanize.downcase %> from being saved
  </h2>
  <p>There were problems with the following fields:</p>
  <ul>
  <% object.errors.full_messages.each do |message| %>
   <li><%= message %></li>
  <% end %>
  </ul>
 </div>


<% end %>

除此之外,我还会对空白字段使用Javascript / HTML5验证。减少带宽使用。 希望这会有所帮助。

相关问题