Ruby on Rails - 验证成本

fre*_*est 34 validation ruby-on-rails

验证用户的成本/价格输入的最佳方法是什么,验证规则如下:

  • 格式示例允许.23,.2,1.23,0.25,5,6.3(小数点后最多两位数)
  • 最小值0.01
  • 最大值9.99

rwi*_*ams 69

检查价格并验证格式

#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/
Run Code Online (Sandbox Code Playgroud)

  • 使用`:greater_than => 0`时要小心.如果数据库字段是例如精度为2的小数,则验证仍将允许值0.00001,该值将在表中保存为0. (4认同)
  • 实际上,你不应该为@Majiy的上述原因使用`:greater_than => 0`,而是使用`:greater_than_or_equal_to => 0.01`. (3认同)
  • 我想你们两个都错过了正则表达式也会捕获像0.00001这样的东西的事实 (3认同)