简体   繁体   中英

Customized validation messages in Ruby on rails

I have a model called user.rb . This model has a customized email validation:

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable, :lockable and :timeoutable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable #,:validatable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me

  validates_presence_of :email,:message=>"El campo email is requerido"

end 

The problem is that the browser shows " Email El campo email is requerido" while I want "El campo email is requerido" (without Email before).

As for Rails newer than 3.2.2, it uses the defined errors.format from the internationalization to build the validation full message.

I believe you cannot change the behavior for just one attribute, but if want to do it for the whole app, you can follow my answer on Customise ActiveModel full_messages

One alternative is to define the message directly to the record's base so it can be printed as it is:

validate do |user|
  user.errors.add :base, 'El campo email is requerido' if user.email.blank?
end

Furthermore, a pull request is open to provide a solution on the attribute level https://github.com/rails/rails/pull/14260

You can use I18n to change the translation of email to "El campo email"

activerecord:
    attributes:
      user:
        email: "El campo email"

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