简体   繁体   中英

Ruby on Rails - Validate a Cost

What is the best way to validate a cost/price input by a user, validation rules below:

  • Examples of formats allowed .23, .2, 1.23, 0.25, 5, 6.3 (maximum of two digits after decimal point)
  • Minimum value of 0.01
  • Maximum value of 9.99

Check the price and verify the format

#rails 3    
validates :price, :format => { :with => /\A\d+(?:\.\d{0,2})?\z/ }, :numericality => {:greater_than => 0, :less_than => 10}

#rails 2
validates_numericality_of :price, :greater_than => 0, :less_than => 10    
validates_format_of :price, :with => /\A\d+(?:\.\d{0,2})?\z/

For client side validations you can use a jQuery plugin like this one that allows you to define different valid formats for a given input.

For server side validations and according to this question/answer maybe you should use a decimal column for price in which you can define values for precision and scale , scale solves the two digits after decimal point restriction.

Then to validate the numericality, minimum and maximum value you can use the next validation method:

validates_numericality_of :price, :greater_than => 0, :less_than => 10

You can build custom validations.Lets say, for example the second case:

validate :price_has_to_be_greater_than_minimum

def price_has_to_be_greater_than_minimum
  errors.add(:price, "price has to be greater than 0.01") if
  !price.blank? and price > 0.01
end

More on this, in the Rails Guides, here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM