自定义验证消息 [英] customize validation messages
问题描述
我想知道如何完全自定义验证消息,这就是我的代码的样子
i want to know how to fully customize validation messages, this is how my code looks like
user_profile.rb:-
user_profile.rb:-
validates: first_name, :presence => {:message => "First name can't be blank"}
但这给了我一条错误消息用户配置文件名字名字不能为空,我想要的是有一条错误消息名字不能为空.我四处寻找解决方案,我想我必须对 en.yml 文件进行一些更改,但我不知道该怎么做.有什么帮助吗?
but this gives me an error message user profile first name First name can't be blank and what i want is to have an error message First name can't be blank. I look around for solution and i think i have to do some changes in en.yml file, but i don't know what to do. Any help?
推荐答案
您有三个选择:
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 会给你 -> ["名字不能为空"]
Doing user_profile.errors.full_messages will give you -> ["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"
有关如何使用语言环境的更多信息,请查看此
For more information on how to use locales, have a look at this
这篇关于自定义验证消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!