Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to validate the number of decimal for a numeric value?

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

like image 858
Mellon Avatar asked Apr 06 '11 07:04

Mellon


3 Answers

You might try this:

validates_format_of :shoe_size, :with => /^\d+\.*\d{0,2}$/
like image 120
Warren Avatar answered Sep 27 '22 21:09

Warren


@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}$/
like image 28
jrich Avatar answered Sep 27 '22 21:09

jrich


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
like image 33
Don Avatar answered Sep 27 '22 23:09

Don