How do I display Ruby on Rails form validation error messages one at a time?

前端 未结 4 541
梦谈多话
梦谈多话 2020-12-02 14:12

I\'m trying to understand how I can achieve this. Can anyone advise me or point me in the right direction?

What I currently do, which is shown in the code snippet be

4条回答
  •  情话喂你
    2020-12-02 14:58

    A better idea,

    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'
    
          "
    "\ "#{self.object.errors[field_name].join(', ')}"\ "
    "\ ""\ "".html_safe end rescue nil end end

    Result

    Markup Generated after error

    
    
    

    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

提交回复
热议问题