简体   繁体   中英

Customizing rails error messages

I have problem with custom messages for validators in rails4. I have app with devise registration system. I have some validators in my model:

 validates :name, length: {maximum: 45}, presence: true
 validates :surname, length: {maximum: 45}, presence: true
 validates :phone, :phony_plausible => true, presence: true
 validates :company_name, length: {maximum: 100}, presence: true
 validates :address, length: {maximum: 50}, presence: true
 validates :city, length: {maximum: 70}, presence: true
 validates :zip_code, presence: true, length: {is: 6}
 validates :nip, nip: true

When user left blank input for name there's a message:

Name can't be blank

When I add a message options to my validator:

  validates :name, length: {maximum: 45}, presence: {message: "Imię nie może być puste"}

I have the following message: Name Imię nie może być puste. I don't want to have this Name word in my message. How to do this?

In your config/locales/en.yml

en: activerecord: attributes: [model_name_goes_here]: [attribute_name_goes here]: "" errors: models: [model_name_goes_here]: attributes: [attribute_name_goes_here]: blank: "Email can't be blank"

Example:

en: activerecord: attributes: user: email: "" errors: models: veteran: attributes: email: blank: "Email can't be blank"

For example, instead of displaying "Email can't be blank" it would display "can't be blank". Essentialy you are replacing the "name:" with an alias that is equal to an empty string. You can set "name:" to name: "Your name"

en: activerecord: attributes: user: name: "Your name"

and it would display "Your name can't be blank"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM