Ruby on Rails - 验证成本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4173530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:37:53  来源:igfitidea点击:

Ruby on Rails - Validate a Cost

ruby-on-railsvalidation

提问by freshest

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
  • 允许的格式示例 .23、.2、1.23、0.25、5、6.3(小数点后最多两位)
  • 最小值 0.01
  • 最大值 9.99

回答by rwilliams

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/

回答by jpemberthy

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

对于客户端验证,您可以使用像这样的 jQuery 插件,它允许您为给定的输入定义不同的有效格式。

For server side validations and according to this question/answermaybe you should use a decimalcolumn for pricein which you can define values for precisionand scale, scalesolves the two digits after decimal point restriction.

对于服务器端验证,根据此问题/答案,您可能应该使用一decimalprice,您可以在其中定义precision和的值scalescale解决小数点限制后的两位数。

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

回答by Shreyas

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.

更多关于这方面的信息,在 Rails 指南中,这里