我在我的应用中使用设计作为身份验证引擎。
设计验证失败时,有没有办法使用自定义消息。
当密码为空时,Devise会向我提供以下消息:Password can't be blank
,但我需要另一条消息。我该怎么办?
答案 0 :(得分:23)
ActiveRecord en.yml是我建议的答案,如果你想更改设计的验证消息
以下是en.yml的外观:
en:
activerecord:
errors:
models:
user:
attributes:
email:
blank: "Please Specify an Email id"
taken: "Please use a different Email id"
invalid: "Please Specify a valid Email id"
password:
blank: "Please Specify a Password"
confirmation: "Password does not match"
password_confirmation:
blank: "Please Specify a Password Confirmation"
first_name:
blank: "Please Specify First Name"
last_name:
blank: "Please Specify Last Name"
pdf:
attributes:
name:
blank: "Please Specify name to PDF"
taken: "Please use different name for PDF"
attachment:
blank: "Please Upload a PDF Attachment"
data_element:
attributes:
name:
blank: "Please give Element a desired name"
taken: "Already Created Element with given name"
color:
blank: "Please assign a color to Element"
template:
attributes:
name:
blank: "Please Specify a Name"
taken: "Please use a different name"
我建议您定义这种方式,而不是自定义设计验证模块
因为如果您遵循上述方法,您可能会跳过验证一两个地方
对于示例I,删除上面的设计验证模块,然后替换您自己的 用户模型
然后所有验证都适用,但您会错过更改密码
中的验证即使密码从未提供也从未给出
,导致您登录保持循环
啦啦队
此致
答案 1 :(得分:2)
请参阅以下网址。
http://railscasts.com/episodes/210-customizing-devise?view=asciicast
如果用户正在登录,则可以在devise.en.yml
下的config/locales
中修改所有错误消息。
如果您正在注册,Devise会自行提供自己的验证,而不进行任何自定义。如果要自定义它,可以编辑User
模型。
查找devise :validatable
并删除:validatable
选项。之后,您应该能够使用常规的rails验证。请注意,这将导致您必须自己进行所有验证。
validates_presence_of :password, :message=>"Your custom error message!"
一些常见的验证:
validates_confirmation_of :password
validates_presence_of :password, :on => :create
validates_presence_of :email
validates_uniqueness_of :email
答案 2 :(得分:0)
不是一个完整的答案,但这听起来应该可以用I18n解决,无论是使用设计内部密钥,还是覆盖用户模型的活动记录验证错误消息。
这是一个类似的问题:Devise attributes for i18n?
答案 3 :(得分:0)
您可以从config / locales / devise.en.yml自定义设计消息,但是如果要更改为验证消息,请删除:来自Model的validatable。然后,您可以像以前一样更改验证消息。 例如:
validates_uniqueness_of :email, :case_sensitive => false, :allow_blank => true, :if => :email_changed?
validates_format_of :email, :with => Devise.email_regexp, :allow_blank => true, :if => :email_changed?
validates_presence_of :password, :on=>:create
validates_confirmation_of :password, :on=>:create
validates_length_of :password, :within => Devise.password_length, :allow_blank => true