[Feature Proposal][PR attached] Create full_message & full_message_format validation option for ActiveModel::Error

Summary

Currently, the default format for a full error message is '%{attribute} %{message}' this can only be changed with the help of locales and i18n for both ActiveModels & ActiveRecords. This new feature adds the ability to format a full error message of an attribute without locales files. It can now be used on any classes that include ActiveModel::Validations and fully formatted error messages can be displayed consistently on web views as:

  • a group with errors.full_messages (on top of a form like the scaffold generator for example)
  • next to their appropriate form field with errors.where(:attribute_name).

This allows more flexibility on the error message displayed to the user while keeping the default validators (presence, uniqueness, inclusionā€¦).

Additionally, It seems that the format required from people is either '%{attribute} %{message}' or '%{message}' this patch adds a full_message option which is a shortcut that uses the full_message_format: '%{message}' option introduced.

Usage

For apps using locales and i18n nothing has changed. For apps that donā€™t rely much on i18n, devs can format full error messages in the model definition.

Here is a description of the new behaviour, existing behaviour still applies.

class Person
  include ActiveModel::Model
  attr_accessor :age, :name

  validates :name, presence: { full_message: 'A person name cannot be blank' }
  validates :age, numericality: {
                                  greater_than_or_equal_to: 18,
                                  message: 'A person must be over 18',
                                  full_message_format: '%{message}'
                                }
end

person = Person.new(age: 17).tap(&:valid?)

person.errors.full_messages
["A person must be over 18", "A person name cannot be blank"]

person.errors.where(:name).map(&:message)
["A person name cannot be blank"]

# works with Errors#add

person = Person.new
person.errors.add(:name, full_message: 'A person name cannot be blank')
person.errors.add(:age, 'A person must be over 18', full_message_format: '%{message}')

person.errors.full_messages
["A person must be over 18", "A person name cannot be blank"]

person.errors.where(:name).map(&:message)
["A person name cannot be blank"]

Here is the proof of concept. Iā€™m happy to finalise the PR with documentation and changelog if this has positive feedback. The PR also provides at the end a gist to test the feature locally .

1 Like