有没有办法在验证函数中将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"> #{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 %>
答案 0 :(得分:4)
输出错误时,请使用raw
<%= raw f.errors %>