【问题标题】:custom validation error messages with html带有 html 的自定义验证错误消息
【发布时间】:2012-04-17 22:05:41
【问题描述】:

有没有办法在 validates 函数中将 html 添加到自定义验证错误消息中?

例如:

class Product < ActiveRecord::Base
  validates :legacy_code, :format => { :with => /\A[a-zA-Z]+\z/,
    :message => "Only letters allowed <a href=\"www.example.com\"> Check here </a> " }
end

执行上述操作只是给出了一个字符串文字,浏览器不会将其解释为带有标签的 html。

我尝试使用语言环境,但这似乎是一种更复杂的方法。我搜索了一堆网站,还尝试覆盖 field_error_proc 方法。

例如:

ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
  errors = Array(instance.error_message).join(',')
  %(#{html_tag}<span class="validation-error">&nbsp;#{errors}</span>).html_safe

end

上述方法有效,但给出的错误消息数量是预期的两倍。

这里的任何帮助将不胜感激。

已解决在错误消息部分中使用 .html_safe:

<% if @user.errors.any? %>
  <div id="error_explanation">
    <div class="alert alert-error">
      The form contains <%= pluralize(@user.errors.count, "error") %>.
    </div>
    <ul>
    <% @user.errors.full_messages.each do |msg| %>
      <li>* <%= msg.html_safe %></li>
    <% end %>
    </ul>
  </div>
<% end %>

【问题讨论】:

  • 只要确保用户没有能力在您的错误消息中添加任何内容而不进行清理。

标签: ruby-on-rails forms validation messages


【解决方案1】:

当你输出你的错误时,使用raw

<%= raw f.errors %>

【讨论】:

  • 嗨凯尔,谢谢。我把这个命令放在哪里?我正在使用 rails 3.2.3,我在表单视图中有这一行:
  • 在你的错误信息中,我想? app/views/shared/_error_messages.*
  • 嗨凯尔,谢谢!我所做的是在错误消息上使用 .html_safe 命令,如上面编辑的问题中所示。你说得对,我必须编辑部分 error_messages 文件:) 2 点赞!
猜你喜欢
  • 2015-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-21
  • 1970-01-01
  • 2016-04-18
  • 2016-12-04
  • 1970-01-01
相关资源
最近更新 更多