【问题标题】:Regex or `nil` in validation验证中的正则表达式或“nil”
【发布时间】:2016-03-08 10:11:59
【问题描述】:

我正在 Rails 中编写此验证:

PRICE_GROUPS.each do |field_number|
  fix_price.validates_format_of :"child_price_group_#{field_number}",
                                :with => /\A\d+\.?\d{0,2}\z/,
                                message: 'Must not be more than 2 decimal places'
end

如何更改它以允许当前的正则表达式或nil?

【问题讨论】:

    标签: ruby-on-rails ruby regex validation


    【解决方案1】:

    您可以使用|:

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

    或

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

    【讨论】:

      【解决方案2】:

      我通过这样做解决了这个问题:

      PRICE_GROUPS.each do |field_number|      
        fix_price.validates_format_of       :"child_price_group_#{field_number}",
                                            :with => /\A\d+\.?\d{0,2}\z/,
                                            message: 'Must not be more than 2 decimal places',
                                            allow_blank: true
      end
      

      【讨论】:

        猜你喜欢
        • 2019-08-03
        • 1970-01-01
        • 1970-01-01
        • 2021-05-07
        • 1970-01-01
        • 1970-01-01
        • 2015-05-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多