如何在字段旁边显示错误消息

时间:2011-04-13 09:09:16

标签: ruby-on-rails devise haml

我有一个带有输入字段/标签等的表单。如何在字段旁边显示错误消息?而不是在顶部聚集在一起?

我正在使用devise,rails 3

我在表格的顶部有这个:

 = form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f|
- if resource.errors.any?
  #errorExplanation
    %h2
      = pluralize(resource.errors.count, "error")
      prevented this user from being saved:
    %ul
      - resource.errors.full_messages.each do |msg|
        %li
          = msg

5 个答案:

答案 0 :(得分:36)

您可以使用此

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

也很有用的链接:

  

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

答案 1 :(得分:6)

只需在初始化文件夹文件夹中创建一个文件。

<强> 配置/初始化/ inline_errors.rb

将此代码放入其中:

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:抱歉我的英文。

答案 2 :(得分:3)

这个怎么样

如果您想将错误消息放在文本字段下方,可以这样做

.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)

什么是error_message_for
- &GT;嗯,这是一个很好的黑客做一些很酷的东西

# 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

<强>结果 enter image description here

标记错误后生成

<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>

对应的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;
        }
      }
    }
  

注意:此处使用Bootstrap变量   并且,在配置目录中对文件进行任何修改后,不要忘记重新启动服务器。

答案 3 :(得分:0)

如果有人正在寻找如何在 Rails 6 中显示特定字段的错误消息的方法:

a = Post.new
a.save # => false
a.errors.full_messages_for(:title)
["Title can't be blank"]

a.errors.full_messages_for(:title).join(', ')
"Title can't be blank, Title too short"

答案 4 :(得分:-1)

您可以使用error_message_on http://apidock.com/rails/ActionView/Helpers/ActiveRecordHelper/error_message_on

更新

form.error_messages已从Rails中删除,现在可以作为插件使用。请使用rails plugin install git://github.com/rails/dynamic_form.git安装。