Ruby on Rails - Validate a Cost

ruby-on-rails, validation

Solution

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/

Problem

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

Original source

Related problems