Low commit activity in last 3 years
A long-lived project that still receives updates
Adds an abstract EachValidator superclass that you can use to create localizable validations.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
 Dependencies

Development

~> 3.0
~> 13.0
>= 1.0

Runtime

 Project Readme

Localized EachValidator

CI Gem Version License: MIT

Author Tim Morgan
License Released under the MIT license.

About

LocalizedEachValidator is a small abstract subclass of ActiveModel::EachValidator that makes it easy to write validators whose error messages are looked up through Rails / ActiveModel's I18n infrastructure.

Subclass LocalizedEachValidator, declare an error_key, and implement #valid?. The validator adds the error key to the record's errors when a value fails validation; ActiveModel will then resolve that key against the standard I18n error message hierarchy.

Installation

Add to your Gemfile:

gem "localized_each_validator"

Or, if you're writing your own validator gem, add it to your gemspec:

spec.add_dependency "localized_each_validator", "~> 2.0"

Then run bundle install.

Usage

Subclass LocalizedEachValidator, set an error_key, and implement #valid?:

class FourValidator < LocalizedEachValidator
  error_key :must_be_four

  def valid?(record, attribute, value)
    value == 4
  end
end

Users of your validator can then add a translation:

en:
  activemodel:
    errors:
      messages:
        must_be_four: "must be four"

Options

LocalizedEachValidator honors the standard EachValidator options:

  • :allow_nil — skip validation when the value is nil.
  • :allow_blank — skip validation when the value is blank.
  • :message — override the default error_key-based error message with a literal string or another symbol.

Default error_key

If you don't call error_key, the default is derived from the class name: the trailing Validator is stripped, the result is demodulized, and underscored. For example, Auth::EmailAddressValidator defaults to :email_address.

See the LocalizedEachValidator class documentation for more details.