Skip to content

Instantly share code, notes, and snippets.

@equivalent
Last active October 1, 2019 21:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save equivalent/4ab2d7a78422d6510faffe59fbde697b to your computer and use it in GitHub Desktop.
Save equivalent/4ab2d7a78422d6510faffe59fbde697b to your computer and use it in GitHub Desktop.
Materialize CSS materialize css Rails form_with input validation
# config/initializers/materialize_form.rb
#
# So that you have Materialize CSS validation message https://materializecss.com/text-inputs.html such as
#
# <div class="input-field">
# <label for="company_title" class="active">Title</label>
# <input type="text" value="" name="company[title]" id="company_title" class="invalid">
# <span data-error="can't be blank" class="helper-text"></span>
# </div>
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
if html_tag =~ /<(input|textarea|select)/
error_class = 'invalid'
doc = Nokogiri::XML(html_tag)
doc.children.each do |field|
if field['type'] != 'hidden' || field['type'] != 'file'
unless field['class'] =~ /\binvalid\b/
field['class'] = [field['class'], 'invalid'].join(' ').strip
end
end
end
if instance.error_message.kind_of?(Array)
err = instance.error_message.uniq.join(', ')
else
err = instance.error_message
end
node_set = Nokogiri::XML::NodeSet.new(doc)
span = Nokogiri::XML::Node.new "span", doc
span['data-error'] = err
span['class'] = "helper-text"
#span.content = "in case you have any concent"
node_set << doc
node_set << span
node_set.to_html.html_safe
else
html_tag
end
end
# app/views/company/new.html.slim
= form_with model: @new_company do |f|
.input-field
= f.label :title, 'Title'
= f.text_field :title
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment