Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 832
freshest Avatar asked Nov 13 '10 16:11

freshest


People also ask

How does validate work in Rails?

Rails validation defines valid states for each of your Active Record model classes. They are used to ensure that only valid details are entered into your database. Rails make it easy to add validations to your model classes and allows you to create your own validation methods as well.

What is the difference between validate and validates in rails?

So remember folks, validates is for Rails validators (and custom validator classes ending with Validator if that's what you're into), and validate is for your custom validator methods.

What happens on Save rails?

The purpose of this distinction is that with save! , you are able to catch errors in your controller using the standard ruby facilities for doing so, while save enables you to do the same using standard if-clauses.


1 Answers

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/ 
like image 131
rwilliams Avatar answered Sep 27 '22 19:09

rwilliams