Skip to content
Skieloch edited this page Aug 22, 2011 · 6 revisions

Error Rendering

Out of the box Client Side Validations will use ActionView::Base.field_error_proc to wrap the inputs and labels that fail validation. You can override this preset template in config/initializers/client_side_validations.rb

The default will take html such as:

<label for="person_name">Name</label>
<input id="person_name" name="person[name]" type="text">

And wrap it like:

<div class="field_with_errors"><label for="person_name">Name</label></div>
<div class="field_with_errors"><input id="person_name" name="person[name]" type="text"></div>

You can then apply styles to any div.field_with_errors elements.

However, by default Rails does not include the error messages. Most people are used to using the error_messages_on method from dynamic_form. Client Side Validations does not and never will support a solution similar to error_messages_for. If you want to render the error messages you should modify ActionView::Base.field_error_proc

The quickest way to do this is to uncomment the code in config/initializers/client_side_validations.rb It should look something like 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

Restart your web server and now you'll get fields wrapped like this:

<div class="field_with_errors"><label for="person_name">Name</label></div>
<div class="field_with_errors"><input id="person_name" name="person[name]" type="text"><label for="person_name">Error Message</label></div>

This includes the error message in a label tag immediately after the input field.

Clone this wiki locally