# [Ruby On Rails]使用i18n客製化表單驗證的錯誤訊息 ###### tags: `Ruby On Rails` 參考網址: https://stackoverflow.com/questions/17935597/ruby-on-rails-i18n-want-to-translate-custom-messages-in-models # MODEL models/article.rb ```ruby= class Article < ApplicationRecord validates :title, presence: true, length:{minimum:5,too_short: :en_article_title_too_short} end ``` # VIEW views/articles/new.html/erb ```ruby= <h2>new articles</h2> <%= form_for :article ,url:articles_path do |f| %> <% if @article.errors.any? %> <ul> <% @article.errors.full_messages.each do |msg| %> <li><%=msg%></li> <% end %> </ul> <% end %> <p> <%= f.label :title,"TITLE" %><br> <%= f.text_field :title %> </p> <p> <%= f.label :text, "text" %><br> <%= f.text_area :text %> </p> <p> <%= f.submit "SAVE"%> </p> <% end %> ``` # CONTROLLER controllers/articles_controller.rb ```ruby= #... def new @article=Article.new end def create @article=Article.new(article_params) # form validation if @article.save redirect_to @article else render 'new' #maintain user input end end private def article_params params.require(:article).permit(:title,:text) end ``` # i18n config/locales/en.yml ```yaml= en: errors: format: "%{message}" activerecord: errors: models: article: # or namespace/model_name attributes: title: en_article_title_too_short: "title format incorrect(at least 5 character)" ```