使用 Rails 完全自定义验证错误消息 [英] Fully custom validation error message with Rails
问题描述
使用 Rails 我试图在保存时收到一条错误消息,如歌曲字段不能为空".执行以下操作:
Using Rails I'm trying to get an error message like "The song field can't be empty" on save. Doing the following:
validates_presence_of :song_rep_xyz, :message => "can't be empty"
... 只显示Song Rep XYW can't be empty",这不好,因为字段的标题对用户不友好.如何更改字段本身的标题?我可以更改数据库中字段的实际名称,但我有多个歌曲"字段,我确实需要有特定的字段名称.
... only displays "Song Rep XYW can't be empty", which is not good because the title of the field is not user friendly. How can I change the title of the field itself ? I could change the actual name of the field in the database, but I have multiple "song" fields and I do need to have specific field names.
我不想绕过 rails 的验证过程,我觉得应该有办法解决这个问题.
I don't want to hack around rails' validation process and I feel there should be a way of fixing that.
推荐答案
现在,设置人性化名称和自定义错误消息的公认方法是 使用语言环境.
Now, the accepted way to set the humanized names and custom error messages is to use locales.
# config/locales/en.yml
en:
activerecord:
attributes:
user:
email: "E-mail address"
errors:
models:
user:
attributes:
email:
blank: "is required"
现在人性化名称和email"属性的存在验证消息已更改.
Now the humanized name and the presence validation message for the "email" attribute have been changed.
可以为特定模型+属性、模型、属性或全局设置验证消息.
Validation messages can be set for a specific model+attribute, model, attribute, or globally.
这篇关于使用 Rails 完全自定义验证错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!