DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Customize ActiveRecord Validation Display To The Extreme

03.09.2006
| 8295 views |
  • submit to reddit
        Modify how form helpers such as 'text_field' handle errors in the following way:

* errors are shown after the input fields (not on top of the form)
* each error can have an explanation on top of the form (only when using custom validator methods)

A custom error SPAN with a nice arrow *after* the input tag, and handle multiple errors for one field (in environment.rb)
ActionView::Base.field_error_proc = Proc.new {|html_tag, instance|
  if instance.error_message.kind_of?(Array)
    %(#{html_tag}<span class='validation-error'>←#{instance.error_message.join(',')}</span>)
  else
    %(#{html_tag}<span class='validation-error'>←#{instance.error_message}</span>)
  end
  }

In your model e.g. order.rb, add a custom validation function (to demonstrate multiple errors on one field)
  private
  
  validate :not_nicky_and_length
  
  def not_nicky_and_length
    if name =~ /Nicky/
      errors.add('name', 'No Nicky, no') # adds the error to the field
      errors.add('name-explanation', "we don't need your business when you're the infamous Russian gangster Nicky") # adds a general error explanation
    end
    if name.length > 2
      errors.add('name', 'Too long')
    end
  end

Add the error notice and explanation before your form 
<h1><%= pluralize(@order.errors.count, "error")%> prohibited this Order from being saved</h1>
<%= error_message_on "order", "name-explanation", "Name: ", nil, "inputError" %>