【问题标题】:Rails: Regex not working in number format validationRails:正则表达式在数字格式验证中不起作用
【发布时间】: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 上按预期工作。

标签: ruby-on-rails validation


【解决方案1】:

问题是 Rails 正在自动执行 typecasting,因为我的数据库已将列设置为 decimal, precision: 5, scale: 3

为了正确验证输入,我需要运行此验证:

validates :modifier_before_type_cast, presence: true, format: { with: /\A\d+(?:\.\d{0,3})?\z/ }, numericality: { less_than: 100_000 }

我最相关的帮助最终来自这里:validation before attribute setters can type cast

【讨论】:

    【解决方案2】:

    尝试以下方法:

    validates :modifier, presence: true, format: { with: /\A\d+(\.\d{0,3})?$/ }, numericality: { less_than: 100_000}
    

    【讨论】:

    • 失败的测试仍然失败,123456测试也失败。这是一条重要的错误消息(我使用的是 Rails 5):ArgumentError: The provided regular expression is using multiline anchors (^ or $), which may present a security risk. Did you mean to use \A and \z, or forgot to add the :multiline => true option?
    • 感谢您的反馈,看看!
    • @JayQuigley 试试我更新的内容。我测试时 123456 测试通过了,如果不适合你,请告诉我
    【解决方案3】:

    您的validates 中的正则表达式似乎不起作用。

    这个表达式有效

    /\A\d+(?:\.?\d{0,3})\z/
    

    在模型中

    validates :modifier, presence: true, format: { with: /\A\d+(?:\.?\d{0,3})\z/ }, numericality: { less_than: 100_000}
    

    【讨论】:

    • 虽然此代码 sn-p 可以解决问题,包括解释 really helps 以提高您的帖子质量。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人!请edit您的答案添加解释,并说明适用的限制和假设。
    【解决方案4】:

    这个适用于许多国家,你可以用或不用空格来写它(\s*):

    validates :bank_account, allow_blank: true, uniqueness: true, format: { with: /\A[a-zA-Z]{2}[0-9]{2}\s*[a-zA-Z0-9]{4}\s*[0-9]{4}\s*([a-zA-Z0-9]?){0,12}\s*[0-9]{4}\z/}
    

    这是它适用于的国家/地区的非详尽列表:比利时、克罗地亚、法国、德国、卢森堡、荷兰、波兰、罗马尼亚、西班牙。我用这个有用的工具在网上查了一下https://regexr.com/

    它不适用的国家之一是保加利亚。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-25
      • 1970-01-01
      • 2021-06-18
      • 2018-11-29
      • 2014-04-21
      • 1970-01-01
      • 2016-08-01
      • 2011-03-01
      相关资源
      最近更新 更多