Home > Back-end >  Float validation on Rails
Float validation on Rails

Time:06-09

Im trying to add validation that prevents a user from entering more than 6 digits before the decimal place, and only 3 after the decimal place. I have precision set up at 8 with a scale of 2, however it is producing an error page. I just want to stop user's from entering anything more than the format set. I have max length already set to 9.

CodePudding user response:

Well your precision and scale are off. Based on your description it should be (9,3) rather than (8,2).

Then the following should work:

class MyClass < ApplicationRecord
  validates :my_float, numericality: {less_than: 1_000_000.0, greater_than_or_equal_to: 0.001}
end 

This will validate that the number is less than 1 Million (6 digits to the left of the decimal) and greater than or equal to 0.001 three digits to the right of the decimal. If you need to handle negative numbers this could get a bit more interesting.

You could also possibly go with something like:

class MyClass < ApplicationRecord
  validates :my_float, format: { with: /-?\d{1,6}\.\d{1,3}/}
end 

Validate optional negative followed by 1-6 digits followed by a period followed by 1-3 digits.

  • Related