LoginSignup
3
2

More than 5 years have passed since last update.

自作バリデータ のエラーメッセージを多言語化する

Posted at

組み込みのバリデーションのエラーメッセージを多言語化する方法はよく見るけど自作のバリデータ の場合の方法って意外と見かけない気がしたので。

前提

  • Userモデルがあり、nameemailpasswordカラムを持っている
  • passwordは半角英数字両方を含む必要がある

バリデーションメソッドの実装

まずは普通に日本語のエラーメッセージを返すバリデーションメソッドを実装する

app/models/user.rb
class User < ApplicationRecord

# 省略

  validate :check_password_format

  def check_password_format
    unless password =~ /\A(?=.*?[a-z])(?=.*?\d)[a-z\d]+\z/i
      errors.add(:password, 'は半角英数字両方を含んでいるもののみ有効です')
      return
    end
  end

end

エラーメッセージの多言語化

翻訳ファイルの用意

日本語と英語の翻訳ファイルを用意する

config/locals/models/user/ja.yml
ja:
  activerecord:
    models:
      user: ユーザー
    attributes:
      user:
        name: 氏名
        email: メールアドレス
        password: パスワード
    errors:
      messages:
        invalid_password: は半角英数字両方を含んでいるもののみ有効です
config/locals/models/user/en.yml
en:
  activerecord:
    models:
      user: User
    attributes:
      user:
        name: Name
        email: Email Address
        password: Password
    errors:
      messages:
        invalid_password: must contain both alphameric and numeric characters

エラーメッセージの呼び出し

app/models/user.rb
class User < ApplicationRecord

# 省略

  validate :check_password_format

  def check_password_format
    unless password =~ /\A(?=.*?[a-z])(?=.*?\d)[a-z\d]+\z/i
      errors.add(:password, :invalid_password)
      return
    end
  end

end

t( user.errors.messages.invalid_password ) と書かなくても、errors.addt( user.errors.messages ) までは呼ばれているということなんだと思う。
最初見たときパッとわからなかったが気づいたときにアハ体験だった。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2