Skip to content

Commit

Permalink
Make the form compatible with Bootstrap server side validation tools
Browse files Browse the repository at this point in the history
  • Loading branch information
danidoni committed Aug 8, 2024
1 parent 007353b commit 4d28a9a
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
= form.label(:name, 'Name:', class: 'form-label')
= form.text_field(:name, class: classes_with_validation(label_template, :name))
- label_template.errors.where(:name).each do |error|
.error-message= error.message.capitalize
.invalid-feedback= error.message.capitalize
.mb-3#color
= form.label(:color, 'Color:', class: 'form-label')
= form.color_field(:color, class: classes_with_validation(label_template, :color))
- label_template.errors.where(:color).each do |error|
.error-message= error.message.capitalize
.invalid-feedback= error.message.capitalize
8 changes: 8 additions & 0 deletions src/api/config/initializers/field_with_errors.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Rails form helpers wrap controls with a .field_with_errors class that prevents the validation styles from bootstrap to work.
# This snippet replaces the wrapping with that class with an injection of .is-invalid class, which is bootstrap compatible.
ActionView::Base.field_error_proc = proc do |html|
frag = Nokogiri::HTML5::DocumentFragment.parse(html)
klass = frag.children[0].attributes['class']
frag.children[0].attributes['class'].value = [klass, 'is-invalid'].join(' ')
frag.to_html.html_safe # rubocop:disable Rails/OutputSafety The input is code from our views, so it's safe to disable this
end

0 comments on commit 4d28a9a

Please sign in to comment.