如何在 rails 输入字段中显示输入字段错误消息 [英] How to show input field error message in rails input field

查看:32
本文介绍了如何在 rails 输入字段中显示输入字段错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

错误消息未仅显示突出显示的字段

Error message not showing only field highlighted

 <%= f.text_field :website,:required=>true,:pattern=>'https?://.+' %>

我如何显示?

推荐答案

选项 1(推荐):使用 simple_form gem.它可以轻松地在字段旁边显示错误消息.安装 gem 后,您可以简单地执行以下操作:

Option 1 (recommended): use simple_form gem. It makes it easy to display error messages next to the fields. After installing the gem, you can then simply do this:

<%= f.input :website %>

选项 2:自己编码.像下面这样的东西将是一个开始.您可能想要添加一些 CSS 类来设置样式,并决定在字段中出现多个错误时该怎么做.

Option 2: code it yourself. Something like the following would be a start. You'll probably want to add some CSS classes for styling, and decide what to do if multiple errors are present on the field.

<%= form_for @model do |f| %>
  <%= f.text_field :website %>
  <%= @model.errors.full_messages_for(:website).join(', ') if @model.errors.has_key?(:website) %>
<% end %>

附注

如果 @model 没有与 website 字段相关联的验证错误,则上述方法将不起作用.这通常不是 Rails 内置验证的问题.即,如果您执行诸如 validates_presence_of :website 之类的操作,那就太好了.但如果您有自定义验证,请确保在调用 errors.add 时在 website 字段中添加错误,例如:

Side note

The above won't work if @model does not have validation errors associated with the website field. This is typically not a concern with Rails built-in validations. I.e., if you do something like validates_presence_of :website - you're good. But if you have custom validations, make sure to add the errors on the website field when calling errors.add, like:

def some_custom_validator
  errors.add(:website, 'Something is wrong') if some_logic
end

如果您的 Rails 或自定义验证在 :base 上添加错误 (errors.add(:base, 'some global issue'),您可能还希望有一些全局错误显示在顶部,如此处所述.

If your Rails or custom validations add errors on :base instead (errors.add(:base, 'some global issue'), you may also want to have some global errors displayed at the top as described here.

这篇关于如何在 rails 输入字段中显示输入字段错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆