Error messages for Rails custom validation

Posted by pikemsu28 on Fri, 31 Jan 2020 14:53:28 +0100

The default error messages of Active Record authentication assistant methods are all in English. In order to improve the user experience, sometimes we are often required to display error messages according to specific text. There are two ways to achieve this.

1. Directly add a copy in: message

class User < ActiveRecord::Base
 validates :email,
presence: { message: 'Mailbox cannot be empty!' },
uniqueness: { message: 'mailbox %{value} Already exist!' }
validates :name,
presence: { message: 'Name cannot be empty!' },
length: { maximum: 255, too_long: 'Names can be up to 255 characters' }
end

To verify:

user = User.new
user.valid?
user.errors.messages
#=> { :email=>["Mailbox cannot be empty!"], :name=>["Name cannot be empty!"]} 

2. Use rails international API

There is already a default en.yml file under the config/locales file. We can add another zh-CN.yml file for Chinese translation

class ApplicationController < ActionController::Base
  before_action :set_locale
  def set_locale
     I18n.locale = user_locale
    # after store current locale
    cookies[:locale] = params[:locale] if params[:locale]
  rescue I18n::InvalidLocale
    I18n.locale = I18n.default_locale
  end

  protected
  def user_locale
    params[:locale] || cookies[:locale] || http_head_locale || I18n.default_locale
  end
  def http_head_locale
request.env['HTTP_ACCEPT_LANGUAGE']
end
end

Set the translation value corresponding to each key

zh-CN:
  activerecord:
    attributes:
      taken: 'Occupied'
      blank: 'Can not be empty'
      user:
        email: 'mailbox'
        password: 'Password'
        name: 'Full name'
        mobile: 'Cell-phone number'
    models:
      user: 'user'
    errors:
      messages:
        record_invalid: "%{errors}"
        taken: 'Occupied'
        blank: 'Can not be empty'
      attributes:
        version: 'Edition'
  actions:
    create: 'Newly added'
    update: 'modify'
    destroy: 'delete'

To verify:

class User < ActiveRecord::Base
  validates :mobile,
            presence:   true,
            uniqueness: true,
end
user = User.new
user.valid?
user.errors.messages  #=> { :mobile=>["Can not be empty", "Occupied"] } 
user.errors.full_messages  #=> [ "Mobile number cannot be empty", "Phone number occupied"]

Reference resources:

Handling validation errors

Translation of Active Record model

Topics: Ruby Mobile