I have my validation in the modle like follows:
validates_numericality_of :shoe_size, :message=>'Please input a number'
But this is not enough because user can input some value like "42.22222222121212121212..." which is not expected. So, how to validate the input to have only two decimals like 42.22
You might try this:
validates_format_of :shoe_size, :with => /^\d+\.*\d{0,2}$/
@warren answer but take out the * and put a ? because you could do 3.....0 but with ? you can have zero or one.
:with => /^\d+\.?\d{0,2}$/
Building off of @Bitterzoet's answer, but still making it a validation (via the validate
method):
class Product < ApplicationRecord
# Whatever other validations you need:
validates :price, numericality: {greater_than_or_equal_to: 0}
# then a custom validation for precision
validate :price_is_valid_decimal_precision
private
def price_is_valid_decimal_precision
# Make sure that the rounded value is the same as the non-rounded
if price.to_f != price.to_f.round(2)
errors.add(:price, "The price of the product is invalid. There should only be two digits at most after the decimal point.")
end
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With