简体   繁体   中英

How to show devise error messages one by one

I'm writing an app and I'm using devise for signup and login purposes.

I'm now validating registration form fields and I can check and show the "non-validated" data by using the "<%= devise_error_messages! %>".

The thing is that I don't want to show all the errors in the same div, I'd like to put error 1 in one div, error 2 in another div and so on.

For example: If an user insert an already taken username and leave the email field empty, I'd like to show:

  1. "Username already taken" close to the username field
  2. "Email can't be blank" close to the email field

Thank you

You can always iterate over the errors in the resource.

So if you for looks similar to this:

<%= form_for(resource, :as => resource_name, :url => registration_path(...

You can simple, get the errors inside the resource and show them, like so:

<% resource.errors.full_messages.each do |msg| %>
  <div><%= msg %></div>
<% end %>

errors.full_messages - will give you an array with nice errors messages that you can display to the user.

I solved it creating an initializer with this

ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|   unless html_tag 
=~ /^<label/
    %{<div class="field_with_errors">#{html_tag}<label for="#{instance.send(:tag_id)}" 
class="message">#{instance.error_message.first}</label></div>}.html_safe else
    %{<div class="field_with_errors">#{html_tag}</div>}.html_safe   end end

This gave me the exact result that I was looking for.

Result

Thanks for your help! :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM