Reputation: 1470
I'm defining the validation of some of my fields present in a table called "Contacts":
class Contact < ActiveRecord::Base
validates :nome, :cognome, :indirizzo_abitazione,
:numero_civico, :indirizzo_email, :prefisso_cellulare, :cellulare, presence: true
validates :nome, :cognome, :indirizzo_email,
:prefisso_cellulare, :cellulare, uniqueness: true
validates :indirizzo_email, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, on: :create }
end
I want to exploit the bootstrap's class attribute 'has-error' to highlight a specific field in red if an error is present; so I tried to do this in this way:
<div class="form-group <%= @contact.errors[:name] ? "has-error" : "" %>" >
<%= f.label :name , :class => "control-label" %><br>
<%= f.text_field :name, :class => "form-control" %>
</div>
But when I log to this page the field is already red. Is there a method to see if, during the validation of one record, a specific field presents an error?
Upvotes: 5
Views: 3304
Reputation: 659
@contact.errors[:name]
returns an array of messages, if no messages are inside then @contact.errors[:name]
will return only an empty array. An array is an object so your statement will always yield "has-error"
.
This will work:
<%= @contact.errors[:name].present? ? "has-error" : "" %>
Upvotes: 5
Reputation: 583
With @contact.errors[:name] ? "has-error" : ""
, you're printing has-error
if @contact.errors[:name]
is not nil. I think it's just empty.
Try to do @contact.errors[:name].blank? ? "" : "has-error"
which means if it's blank (equivalent to 'is nil or empty'), don't add the class, else add the required class.
Upvotes: 0