验证中使用正则表达式或“nil”

时间:2015-12-03 17:08:13

标签: ruby-on-rails ruby regex validation

我在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

2 个答案:

答案 0 :(得分:2)

您可以使用|执行此操作:

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

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

答案 1 :(得分:1)

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

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
相关问题