问题描述
这看起来应该很简单.注册新用户时,我想要空白用户名和密码的自定义错误.它适用于用户名:
It seems like this should be straightforward. When signing up new users, I want custom errors for blank user names and passwords. It worked fine for the user name:
validates :name, presence: { message: "Please enter a name." },
length: { maximum: 50,
message: "Please enter a name shorter than 50 characters"}
当该字段为空时,它会显示请输入名称".错误.
When the field is blank, it gives the "Please enter a name." error.
密码也一样:
has_secure_password
validates :password, presence: { message: "Please enter a password." },
length: { minimum: 8,
message: "Please choose a password with at least 8 \
characters."}
最小长度消息工作正常.但是,如果我使用空密码提交,则会收到默认的不能为空"消息.
The minimum length message works fine. But if I submit with an empty password, I get the default "can't be blank" message.
推荐答案
has_secure_password validations: false 起初有效,但在编辑用户配置文件页面时遇到问题.它假定用户可能没有输入密码.所以这取决于 has_secure_password 中的验证,上面的答案禁用了.
has_secure_password validations: false worked at first, but I had a problem when I made the edit user profile page. It assumes the user might not enter a password. So it depends on the validations in has_secure_password, which the answer above disables.
更好的方法是编辑 config/local/en.yml:
A better way is to edit config/local/en.yml:
en:
activerecord:
attributes:
user:
password: "Password"
errors:
models:
user:
attributes:
password:
blank: "Please enter a password."
这篇关于密码存在验证的自定义错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!