Extend NumericalityValidator to check precision and scale

Use new checks on Unit.multiplier
Closes #28
This commit is contained in:
2024-12-07 20:16:43 +01:00
parent 25ac126df9
commit 15a5515c99
5 changed files with 27 additions and 2 deletions

View File

@@ -0,0 +1,16 @@
module CoreExt::ActiveModel::Validations::NumericalityValidatesPrecisionAndScale
def validate_each(record, attr_name, value, ...)
super(record, attr_name, value, ...)
if options[:precision] || options[:scale]
attr_type = record.class.type_for_attribute(attr_name)
value = BigDecimal(value) unless value.is_a? BigDecimal
if options[:precision] && (value.precision > attr_type.precision)
record.errors.add(attr_name, :precision_exceeded, **filtered_options(attr_type.precision))
end
if options[:scale] && (value.scale > attr_type.scale)
record.errors.add(attr_name, :scale_exceeded, **filtered_options(attr_type.scale))
end
end
end
end