【发布时间】:2011-05-09 13:56:51
【问题描述】:
验证用户输入的成本/价格的最佳方法是什么,验证规则如下:
- 允许的格式示例 .23、.2、1.23、0.25、5、6.3(小数点后最多两位数)
- 最小值 0.01
- 最大值9.99
【问题讨论】:
-
如果用户输入 4.555 你想要什么行为?失败?还是修剪多余的 5 个?
验证用户输入的成本/价格的最佳方法是什么,验证规则如下:
【问题讨论】:
#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/
【讨论】:
:greater_than => 0时要小心。例如,如果数据库字段是精度为 2 的小数,则验证仍将允许值 0.00001,该值将在表中保存为 0。
:greater_than => 0,而应该使用:greater_than_or_equal_to => 0.01。
nil 小数点后两位以上:/\A\d+(?:\.\d{0,2})?\z/
您可以构建自定义验证。比方说,例如第二种情况:
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
更多信息,在 Rails 指南中,here。
【讨论】:
validates :price, :numericality => { :greater_than => 0.01, :allow_blank => true }。与第一次验证相同——您正在针对 Regexp 进行验证,Rails 已经使用 validates :price, :format => ... 提供了它
对于客户端验证,您可以使用像 this one 这样的 jQuery 插件,它允许您为给定的输入定义不同的有效格式。
对于服务器端验证,根据此question/answer,也许您应该为price 使用decimal 列,您可以在其中定义precision 和scale 的值,scale 解决后面的两位数小数点限制。
然后要验证数值、最小值和最大值,您可以使用下一个验证方法:
validates_numericality_of :price, :greater_than => 0, :less_than => 10
【讨论】:
:greater_than => 0,因为@Majiy提到的原因,而是使用:greater_than_or_equal_to => 0.01。