i want to know how to fully customize validation messages, this is how my code looks like
user_profile.rb:-
validates: first_name, :presence => {:message => "First name can't be blank"}
but this gives me an error message user profile first name First name can't be blank and what i want is to have an error message First name can't be blank. I look around for solution and i think i have to do some changes in en.yml file, but i don't know what to do. Any help?
You have three options:
validate do |user|
user.errors.add_to_base("First name can't be blank") if user.first_name.blank?
end
or
Doing user_profile.errors.full_messages will give you -> ["First Name can't be blank"]
validates: first_name, :presence => {:message => "can't be blank"}
or
# config/locales/en.yml
en:
activerecord:
attributes:
user_profile:
first_name: "First name"
errors:
models:
user_profile:
attributes:
first_name:
blank: "can't be blank"
For more information on how to use locales, have a look at this
Rails uses their own error handling. Which means that it shows the database column. This results into name of column *can't be blank.
Try using something like this and only thing you have to do is change your model.
<% if object.errors.any? %>
<div id="error_explanation">
<h2>
<%= pluralize(object.errors.count, "error") %>
probited this <%= object.class.to_s.underscore.humanize.downcase %> from being saved
</h2>
<p>There were problems with the following fields:</p>
<ul>
<% object.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
Besides that, I'd use Javascript/HTML5 validation for blank fields. To decrease bandwith usage.
Hope this helps.