加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 使用html自定义验证错误消息

发布时间:2020-12-17 02:31:48 所属栏目:百科 来源:网络整理
导读:有没有办法在验证函数中添加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到自定义验证错误消息?

例如:

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 %>

解决方法

输出错误时,请使用raw

<%= raw f.errors %>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读