Ruby-on-rails 验证非负整数和十进制值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11806498/
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
Validation for non-negative integers and decimal values
提问by Sneha Kachroo
My fields are:
tax rateand tax amountin which I want to validate positive values.
我的字段是:
tax rate并且tax amount我想在其中验证正值。
I wrote this validation:
我写了这个验证:
:format => { :with => /\A[+]?\d+\Z/}
But it is not taking numbers with a decimal point like 4.67.
And it's throwing me an error.
What type of validation will work on integers and floating point values?
for example: 2, 57, 54.56should pass but -2.56, -87should fail.
但它不会采用像4.67. 它给我一个错误。什么类型的验证适用于整数和浮点值?例如:2, 57,54.56应该通过但是-2.56,-87应该失败。
回答by dimuch
Doesn't this work?
这不行吗?
validates :your_field, :numericality => { :greater_than_or_equal_to => 0 }
(guess for taxes following rule will be more correct:)
(按照规则猜测税收会更正确:)
validates :your_field, :numericality => { :greater_than_or_equal_to => 0, :less_than_or_equal_to => 100 }
回答by Oswaldo Ferreira
You could use:
你可以使用:
validates :tax_rate, inclusion: { in: 0..5 }
It allows values like: 0, 2, 1.2, 3.2
它允许如下值:0, 2, 1.2, 3.2
Hope it helps!
希望能帮助到你!
回答by Justin
you could use validates_numericality_of :amount, :greater_than => 0.0
你可以用 validates_numericality_of :amount, :greater_than => 0.0

