【问题标题】:Rails: Why "format" (regex) validation fails?Rails:为什么“格式”(正则表达式)验证失败?
【发布时间】:2010-12-17 02:40:06
【问题描述】:

我对产品的价格进行了以下验证:

class Product < ActiveRecord::Base
    ...
    PRICE_REGEX = /^([1-9]\d{0,5}|0)(\.\d{1,2})?$/
    validates :price, :presence => true, :format => PRICE_REGEX
    ...
end

它应该允许从0999999.99 的价格。

但是,如果我输入hello,则验证通过,并且0.00 会保存在数据库中。

不过,:presence 验证工作正常。

我在这里错过了什么?

【问题讨论】:

    标签: ruby-on-rails regex validation ruby-on-rails-3


    【解决方案1】:

    price 列是一个浮点数,因此 Rails 会根据"hello".to_f # =&gt; 0.0 自动将字符串“hello”转换为浮点数。然后将其转换回字符串"0.0",这显然与正则表达式匹配。

    一般来说,在非字符串列上使用正则表达式是个坏主意。相反,请使用validates_numericality_of。如果您想要与正则表达式相同的限制,请这样做:

    class Product < ActiveRecord::Base
      validates_numericality_of :price, :greater_than => 0, :less_than => 1000000
    end
    

    它不仅更安全,而且更易于阅读和遵循。请注意,如果为空白,它也会自动拒绝价格。

    【讨论】:

      【解决方案2】:

      我没有对此进行测试,但是我从 validates 中看到的每个描述都以这种方式使用 :format:

      validates :price, :presence => true, :format => { :with => PRICE_REGEX }
      

      也许问题出在那儿

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-03-29
        • 1970-01-01
        • 1970-01-01
        • 2019-06-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-20
        相关资源
        最近更新 更多