Ruby on Rails - Validate a Cost

匿名 (未验证) 提交于 2019-12-03 08:28:06

问题:

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

回答1:

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/ 


回答2:

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 


回答3:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!