LoginSignup
11
12

More than 5 years have passed since last update.

[Rails] バリデーションエラーが発生した場合、そのフォーム要素自体にクラスを付与する

Last updated at Posted at 2016-11-07

Railsでは、バリデーションエラーが発生した場合、デフォルトで.field_with_errorsというクラスがついたdivで囲んだ状態でラベルとフォームの要素(input, textarea, select)などを出力する。

それを変更したい場合は、application.rb内でconfig.action_view.field_error_procにProcを渡してやれば良い。

やりたいこと

エラーがある場合、クラスを付与したdivでその要素を囲むのではなく、その要素自体にクラスを付与したい。

実装

application.rb
config.action_view.field_error_proc = Proc.new do |html_tag, instance|
      if instance.kind_of?(ActionView::Helpers::Tags::Label)
        html_tag.html_safe
      else
        Nokogiri::HTML.fragment(html_tag).search('input', 'textarea', 'select').add_class('is-error').to_html.html_safe
      end
    end

やっていること

instance.kind_of?(ActionView::Helpers::Tags::Label)で、labelタグかどうか調べている。ラベルなら何もしない。
・それ以外の場合、Nokogiriでhtml_tagをパースし、クラスを付与する。

参考:
http://qiita.com/youcune/items/76a50ae3a2863a8f8b00

11
12
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
11
12