Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Show Error Messages Next to Field

I have a form with input fields/labels etc. How do I get the error message to show up next to the field? instead of clumped together at the top?

I am using devise, rails 3

I have this at the top of my form:

 = form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| - if resource.errors.any?   #errorExplanation     %h2       = pluralize(resource.errors.count, "error")       prevented this user from being saved:     %ul       - resource.errors.full_messages.each do |msg|         %li           = msg 
like image 216
newbie_86 Avatar asked Apr 13 '11 09:04

newbie_86


People also ask

Where can I display error messages?

The two most common placements for error messages are at the top of the form and inline with erroneous fields. Which placement is more intuitive for users? A research study discovered that displaying all error messages at the top of the form puts a high cognitive load on user memory.

How do I display error message below input field?

To customize the appearance and text of these messages, you must use JavaScript; there is no way to do it using just HTML and CSS. HTML5 provides the constraint validation API to check and customize the state of a form element. var email = document. getElementById("mail"); email.

How do I display validation error?

You may also use the @error Blade directive to quickly check if validation error messages exist for any given attribute. This method will add class (is-invalid) to the attribute if a validation error message exists for this particular attribute.


2 Answers

You can use this

- if @resource.errors[:field_name]   ... 

Also useful link:

http://guides.rubyonrails.org/active_record_validations.html#working-with-validation-errors

like image 160
fl00r Avatar answered Sep 20 '22 03:09

fl00r


Just create a file in your initializers folder.

config/initializers/inline_errors.rb

Place this code in it:

ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|   unless html_tag =~ /^<label/     %{<div class="has-error">#{html_tag}<span class="help-block">#{instance.error_message.first}</span></div>}.html_safe   else     %{#{html_tag}}.html_safe   end end 

PD: Sorry for my english.

like image 42
el_quick Avatar answered Sep 24 '22 03:09

el_quick