【发布时间】:2016-10-31 17:45:16
【问题描述】:
在 Rails 5 验证中,我试图确保输入的浮点数在小数点后最多有 3 位。部分关注this thread 我有
validates :modifier, presence: true, format: { with: /\A\d+(?:\.\d{0,3})?\z/ }, numericality: { less_than: 100_000}
但以下测试失败(使用shoulda matchers gem):
should_not allow_value(12345.1234).for(:modifier)
错误信息:Expected errors when modifier is set to 12345.1234, got no errors
即使以下测试成功:
should allow_value(12345.123).for(:modifier)
should allow_value(12345).for(:modifier)
should_not allow_value(123456).for(:modifier)
可能它与仅适用于字符串的正则表达式有关,而我正在使用的 :modifier 属性是作为浮点数出现的。所以我需要找到一种方法来在浮点的字符串化版本上运行验证......
【问题讨论】:
-
查看 Rubular 以测试正则表达式! rubular.com
-
我提供的正则表达式在 Rubular 上按预期工作。