Add multiple_of option to ActiveModel::Validations::NumericalityValidator

Hi :wave:t4:

I recently needed to validate that an attribute on one of my models is a multiple of certain value. Having looked through the numericality validation docs, it doesn’t seem like there’s a way to do this without writing a custom validation. My requirement as a custom validation is something like:

class MyModel
  validates :offset, numericality: { only_integer: true }
  validate :offset_is_a_multiple_of_seven
  
  private

  def offset_is_a_multiple_of_seven
    # multiple_of? is defined on Integer by ActiveSupport
    return if offset.multiple_of?(7) 

    errors.add(:offset, "must be a multiple of 7)
  end
end

I thought it might be useful if the numericality validator handled this. Example:

class MyModel
  validates_numericality_of :offset, multiple_of: 7
end

model = MyModel.new

model.offset = -7
model.valid? # => true

model.offset = 0
model.valid? # => true

model.offset = 7
model.valid? # => true

model.offset = 10
model.valid? # => false

Example for positive values only:

class MyModel
  validates_numericality_of :offset, multiple_of: 7, greater_than: 0
end

model = MyModel.new

model.offset = -7
model.valid? # => false

model.offset = 0
model.valid? # => false

model.offset = 7
model.valid? # => true

model.offset = 10
model.valid? # => false

I thought I’d create this topic to check if this is a generic enough requirement to implement. I’ve already got a PR implementing this if the feedback is positive.

The associated PR was closed as this seems to be a rare use case.