Rails:为什么要“格式化"(正则表达式)验证失败? [英] Rails: Why "format" (regex) validation fails?

查看:42
本文介绍了Rails:为什么要“格式化"(正则表达式)验证失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对产品价格有以下验证:

I have the following validation of product's price:

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.

It supposed to allow prices from 0 to 999999.99.

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

However, if I enter hello, the validation passes, and 0.00 is saved in the database.

:presence 验证工作正常.

我在这里遗漏了什么?

推荐答案

price 列是一个浮点数,所以 Rails 会按照 "hello".to_f # = 自动将字符串 "hello" 转换为浮点数>0.0.然后将其转换回字符串 "0.0",它显然与正则表达式匹配.

The price column is a float, and so Rails will automatically convert the string "hello" to float, as per "hello".to_f # => 0.0. This is then converted back to the string "0.0", which obviously matches the regular expression.

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

In general, it's a bad idea to use regular expressions on non-string columns. Instead, use validates_numericality_of. If you wanted the same restriction as with the regex, do it like this:

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

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

Not only is it safer, but it's easier to read and follow as well. Note that it'll automatically reject the price if blank as well.

这篇关于Rails:为什么要“格式化"(正则表达式)验证失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆