Skip to content

Add `value_format` option to `numericality`, `length`, and `comparison` validators

Created by: techkato

Motivation / Background

In current implementations, formatting numerical or date values in messages generated by validations typically requires specifying the message option or implementing custom validators. However, I only want to format the %{count} and do not need to handle the message, apart from the message option, so I believe it should be a native feature of the framework.

Detail

This pull request introduces the value_format option for validations such as numericality, length, and comparison. With this option, it becomes possible to format the value passed to %{count} in i18n messages.

e.g. messages like "must be equal to 1,000" can now be generated.

class MyModel < ApplicationRecord
  validates :my_attribute, numericality: {
    equal_to: 1_000,
    value_format: -> (value) { value.to_fs(:delimited) }
  }
end

Additional information

There have been several similar PRs submitted in the past:

Comparing them,

  • There is no impact on existing implementation since it can be specified with options.
  • It also supports length and comparison where %{count} is used, not limited to numericality.

If there are any errors or inconsistencies in the English language in the change log or documentation, please point them out.

Checklist

Before submitting the PR make sure the following are checked:

  • This Pull Request is related to one change. Changes that are unrelated should be opened in separate PRs.
  • Commit message has a detailed description of what changed and why. If this PR fixes a related issue include it in the commit message. Ex: [Fix #issue-number]
  • Tests are added or updated if you fix a bug or add a feature.
  • CHANGELOG files are updated for the changed libraries if there is a behavior change or additional feature. Minor bug fixes and documentation changes should not be included.

Merge request reports