Reputation: 570
I have a model with email as one of its attributes. It has the following validation:
validates :email, presence: true, length: { maximum: 50 }, format: { with: VALID_EMAIL_REGEX }
When the user submits the form with an empty empty email, I get the following 2 errors:
How can I display only the first error message related to a field in such a scenario?
I'm retrieving the error messages associated with the object by doing:
@object.errors.full_messages
Upvotes: 0
Views: 877
Reputation: 872
You can do that very easy with this line:
<%= @object.errors.full_messages.first if @object.errors.any? %>
Just replace with your object instance. If you want to use with just one field then there is this method
http://api.rubyonrails.org/classes/ActiveModel/Errors.html#method-i-full_messages_for:
object.errors.full_messages_for(:email)
This will get you specific error for single field
EDIT:
if you have a lot of fields:
<% @object.errors.each do |attr, msg| %>
<%= "#{attr} #{msg}" if @object.errors[attr].first == msg %>
<% end %>
Upvotes: 3