使用html自定义验证错误消息

时间:2012-04-17 22:05:41

标签: ruby-on-rails forms validation messages

有没有办法在验证函数中将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

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

我们将非常感谢您的帮助。

解决在错误消息partial:

中使用.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 %>

1 个答案:

答案 0 :(得分:4)

输出错误时,请使用raw

<%= raw f.errors %>