Reputation: 266
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.
I the same thing for the password:
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.
Upvotes: 3
Views: 5823
Reputation: 266
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.
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."
Upvotes: 2
Reputation: 18833
has_secure_password
automatically adds some validations for you:
Password must be present on creation
Password length should be less than or equal to 72 characters
Confirmation of password (using a password_confirmation attribute)
To prevent that, declare:
has_secure_password validations: false
And then you can add your own.
Upvotes: 3