Show error in field instead of flash/notice

Asked

Viewed 245 times

1

I have a Rails application with Twitter Bootstrap that, when creating a record and presenting errors, shows the error in a flash/notice as per image:imagem

However, I would like errors to appear in the fields, and change the class of inputs to . has-error or something like that. I took a look at field_error_proc and tried to change it in several ways, but to no avail (actually, maybe I did something wrong).

2 answers

1


Using the form helpers

<%= form_for @post |f| %>
  <% @post.errors[:title].join(", ") %>
  <%= f.text_field :title %>
  <%= f.submit "Create" %>
<% end %>

error fields have an output like this:

<div class="field_with_errors">
 <input id="post_title" name="post[title]" size="30" type="text" value="">
</div>

using the class field_with_errors:

.field_with_errors {
  padding: 2px;
  background-color: red;
  display: table;
}

source

  • It’s funny that in my case the fields don’t end up with this class "field_with_bugs", I don’t know if it’s because of bootstrap, simple_form or something else. However, the part of the errors above the input worked.

1

In the case of Bootstrap, it is possible to make the border of fields with a red error with a simple line in jQuery:

$(".form-group:has(.field_with_errors)").addClass("has-error");
  • Great. This can help in case I can’t do this automatically via CSS by merging with Rails errors (because it seems to me that the normal input div would change its class when presenting errors).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.