Reputation: 93
Is there a way to add html to custom validation error messages within the validates function?
For example:
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
Doing the above simply gives a string literal without the browser interpreting it as html with the tag.
I tried using locale but it seems like a more complicated way to do it. I've googled a bunch of websites and also tried to override the field_error_proc method.
For example:
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
The above works but gives twice the number of error messages than intended.
Any help here will be greatly appreciated.
Solved by using .html_safe in error message partial:
<% 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 %>
Upvotes: 4
Views: 2890