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

发布于 2024-10-31 16:17:26 字数 461 浏览 2 评论 0原文

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

我正在使用 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

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, rails 3

I have this at the top of my form:

 = 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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

鹊巢 2024-11-07 16:17:27

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

.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
-->嗯,这是一个漂亮的技巧,可以做一些很酷的事情

# 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

结果
输入图片此处描述

错误后生成的标记

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

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

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
enter image description here

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.

[浮城] 2024-11-07 16:17:27

您可以使用 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 安装它。

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.

埖埖迣鎅 2024-11-07 16:17:27

如果有人正在寻找一种方法来显示 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"

If anyone is looking for a way how to display error messages for particular field in 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"
坏尐絯℡ 2024-11-07 16:17:26

您可以使用这个

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

也有用的链接:

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

You can use this

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

Also useful link:

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

雄赳赳气昂昂 2024-11-07 16:17:26

只需在初始化程序文件夹中创建一个文件即可。

config/initializers/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:抱歉我的英语。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文