Rails的错误提示魔法
# Place this code in a initializer. E.g: config/initializers/form_error.rb ActionView::Base.field_error_proc = Proc.new do |html_tag, instance_tag| fragment = Nokogiri::HTML.fragment(html_tag) field = fragment.at('input,select,textarea') model = instance_tag.object error_message = model.errors.full_messages.join(', ') html = if field field['class'] = "#{field['class']} invalid" html = <<-HTML #{fragment.to_s} <p class="error">#{error_message}</p> HTML html else html_tag end html.html_safe end
来自: https://www.jorgemanrubia.com/2019/02/16/form-validations-with-html5-and-modern-rails/
# config/initializers/fields_with_errors.rb ActionView::Base.field_error_proc = proc do |html_tag, instance| html_doc = Nokogiri::HTML::DocumentFragment.parse(html_tag, Encoding::UTF_8.to_s) element = html_doc.children[0] if element element.add_class('is-invalid') if %w[input select textarea].include? element.name instance.raw %(#{html_doc.to_html} <div class="invalid-feedback">#{[*instance.error_message].to_sentence}</div>) else instance.raw html_doc.to_html end else html_tag end end
来自: https://dev.to/etoundi_1er/show-rails-validation-errors-inline-with-bootstrap-4-4ga6
override of field_error_proc
https://discuss.rubyonrails.org/t/feature-allow-for-override-of-field-error-proc-in-the-formbuilder-could-prepare-pr-if-the-approach-is-reasonable/79843
override of field_error_proc
https://discuss.rubyonrails.org/t/feature-allow-for-override-of-field-error-proc-in-the-formbuilder-could-prepare-pr-if-the-approach-is-reasonable/79843
阅读量: 982
发布于:
修改于:
发布于:
修改于: