我在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
?
答案 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