How to Show Error Messages Next to Field

后端 未结 4 605
花落未央
花落未央 2020-12-13 19:16

I have a form with input fields/labels etc. How do I get the error message to show up next to the field? instead of clumped together at the top?

I am using devise, r

相关标签:
4条回答
  • 2020-12-13 19:22

    How about this

    if you want to put the error message just beneath the text field, you can do like this

    .row.spacer20top
      .col-sm-6.form-group
        = f.label :first_name, "*Your First Name:"
        = f.text_field :first_name, :required => true, class: "form-control"
        = f.error_message_for(:first_name)
    

    What is error_message_for?
    --> Well, this is a beautiful hack to do some cool stuff

    # Author Shiva Bhusal
    # Aug 2016
    # in config/initializers/modify_rails_form_builder.rb
    # This will add a new method in the `f` object available in Rails forms
    class ActionView::Helpers::FormBuilder
      def error_message_for(field_name)
        if self.object.errors[field_name].present?
          model_name              = self.object.class.name.downcase
          id_of_element           = "error_#{model_name}_#{field_name}"
          target_elem_id          = "#{model_name}_#{field_name}"
          class_name              = 'signup-error alert alert-danger'
          error_declaration_class = 'has-signup-error'
    
          "<div id=\"#{id_of_element}\" for=\"#{target_elem_id}\" class=\"#{class_name}\">"\
          "#{self.object.errors[field_name].join(', ')}"\
          "</div>"\
          "<!-- Later JavaScript to add class to the parent element -->"\
          "<script>"\
              "document.onreadystatechange = function(){"\
                "$('##{id_of_element}').parent()"\
                ".addClass('#{error_declaration_class}');"\
              "}"\
          "</script>".html_safe
        end
      rescue
        nil
      end
    end
    

    Result

    Markup Generated after error

    <div id="error_user_first_name" for="user_first_name" class="signup-error alert alert-danger">This field is required.</div>
    <script>document.onreadystatechange = function(){$('#error_user_first_name').parent().addClass('has-signup-error');}</script>
    

    Corresponding SCSS

      .has-signup-error{
        .signup-error{
          background: transparent;
          color: $brand-danger;
          border: none;
        }
    
        input, select{
          background-color: $bg-danger;
          border-color: $brand-danger;
          color: $gray-base;
          font-weight: 500;
        }
    
        &.checkbox{
          label{
            &:before{
              background-color: $bg-danger;
              border-color: $brand-danger;
            }
          }
        }
    

    Note: Bootstrap variables used here and, do not forget to Restart the server now and after any modification to the file in config dir.

    0 讨论(0)
  • 2020-12-13 19:28

    You can use this

    - if @resource.errors[:field_name]
      ...
    

    Also useful link:

    http://guides.rubyonrails.org/active_record_validations.html#working-with-validation-errors

    0 讨论(0)
  • 2020-12-13 19:39

    Just create a file in your initializers folder.

    config/initializers/inline_errors.rb

    Place this code in it:

    ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
      unless html_tag =~ /^<label/
        %{<div class="has-error">#{html_tag}<span class="help-block">#{instance.error_message.first}</span></div>}.html_safe
      else
        %{#{html_tag}}.html_safe
      end
    end
    

    PD: Sorry for my english.

    0 讨论(0)
  • 2020-12-13 19:47

    You can use error_message_on http://apidock.com/rails/ActionView/Helpers/ActiveRecordHelper/error_message_on

    Update:

    form.error_messages was removed from Rails and is now available as a plugin. Please install it with rails plugin install git://github.com/rails/dynamic_form.git.

    0 讨论(0)
提交回复
热议问题