Over a million developers have joined DZone.

Customize ActiveRecord Validation Display To The Extreme

DZone's Guide to

Customize ActiveRecord Validation Display To The Extreme

· ·
Free Resource
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)

In your model e.g. order.rb, add a custom validation function (to demonstrate multiple errors on one field)

  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
    if name.length > 2
      errors.add('name', 'Too long')

Add the error notice and explanation before your form 

<%= pluralize(@order.errors.count, "error")%> prohibited this Order from being saved

<%= error_message_on "order", "name-explanation", "Name: ", nil, "inputError" %>

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}