3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

railsのformのエラー時にdivとかで囲わずにinput要素にclassをつける

Posted at

fireld_error_proc でデフォルトの状態だとエラー時にinput要素の周りをdivで囲われてしまいます。

<div class="field_with_errors">
  <input autofocus="autofocus" autocomplete="email" placeholder="email" type="email" value="" name="user[email]" id="user_email">
</div>

↑こんな感じ
その際に、divで囲うのではなく要素自体に特定のクラス名をつけたい時の書き方

追加手順

nokogiriをinstall

Gemfile
# nokogiri
# https://github.com/sparklemotion/nokogiri
gem 'nokogiri'

application.rbに以下を追加

config/application.rb
# Application class内に追加
config.action_view.field_error_proc = proc do |html_tag, _instance|
  if html_tag.match?(/<(input|label|textarea|select)/)
    html_field = Nokogiri::HTML::DocumentFragment.parse(html_tag)
    html_field.children.add_class 'error'
    html_field.to_s.html_safe
  else
    html_tag.html_safe
  end
end

特定の要素だった場合、nokogiriで特定の文字列をパースしてadd_classをする

出力結果

<input autofocus="autofocus" autocomplete="email" class="error" placeholder="email" type="email" value="" name="user[email]" id="user_email">

参考

3
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?