我正在使用 simple_form 宝石包。当用户无法通过验证时,我想自定义显示的错误信息。我该如何实现这一点?
我正在使用 simple_form 宝石包。当用户无法通过验证时,我想自定义显示的错误信息。我该如何实现这一点?
您可以在您的模型中声明错误消息的内容:
validates_length_of :name, :minimum => 5, :message => "blah blah blah"
你可以为错误标签设置 id
或 class
: <%= f.input :name, :error_html => { :id => "name_error"} %>
然后你可以使用CSS来进行样式设置。
而且你可以使用
<%= f.error :name, :id => "name_error" %>
你将得到
<span class="error" id="name_error">is too short (minimum is 5 characters)</span>
我不知道对于simple_form gem是否有所不同。
如果要更改错误消息的内容,您可以在模型中使用:message
属性。
class User < ActiveRecord::Base
validates :email, {:presence => true, :message => "is not filled up."}
end
电子邮件未填写
。如果您还想更改字段名称(例如将电子邮件
更改为电子邮件地址
),则现在的方法是在locales.rb
文件中定义,如下所示。# config/locales/en.yml
en:
activerecord:
attributes:
user:
email: "E-mail address"
locales
的详细信息。另一种方法是在模型中定义人性化属性,如下所示:class User < ActiveRecord::Base
validates :email, {:presence => true, :message => "is not filled up."}
HUMANIZED_ATTRIBUTES = {
:email => "E-mail address",
...(other fields and their humanized names)
...
}
def self.human_attribute_name(attr, options={})
HUMANIZED_ATTRIBUTES[attr.to_sym] || super
end
end
要定制验证信息的样式,我们需要编辑scaffold.css
样式表中的#errorExplanation
和.fieldWithErrors
的样式。
config/locales/simple_form.en.yml
。config/initializers/simple_form.rb
中,您可以覆盖默认选项以生成html。simple_form.en.yml
中默认错误信息的语法?如果对一个属性有两个验证,例如 :presence => true
和 :format => ...
,你该如何为每个提供不同的错误消息? - Justin Meltzer还有一种解决方案在答案中没有提到,可以在表单本身中直接覆盖视图中的错误消息。例如:这里有详细说明。
<%= f.input :last_name,
placeholder: 'last_name',
error: 'This is a custom error message',
required: true,
class: 'form-field',
autofocus: true,
input_html: { autocomplete: "last_name" } %>
然而,这并不被建议,因为它不符合DRY原则,你需要在每个字段中都进行覆盖。