Skip to content
Browse files

Enhance money validation process

White spaces and underscores are removed by the raw value string,
before it is given to the numericality validator. This ensures
that numbers like 45_555_555 are passing the validation procedure.
  • Loading branch information...
1 parent 85b6878 commit 73b35b256843e1727dd4a7546368c2b9fbbaff2a @alup alup committed Jan 25, 2013
Showing with 18 additions and 5 deletions.
  1. +6 −5 lib/money-rails/active_model/validator.rb
  2. +12 −0 spec/active_record/monetizable_spec.rb
View
11 lib/money-rails/active_model/validator.rb
@@ -50,11 +50,12 @@ def validate_each(record, attr, value)
end
end
- # remove thousands separators
- raw_value = raw_value.to_s.gsub(thousands_separator, '')
-
- # normalize decimal mark
- raw_value = raw_value.to_s.gsub(decimal_mark, '.')
+ # Remove thousands separators, normalize decimal mark,
+ # remove whitespaces and _ (E.g. 99 999 999 or 12_300_200.20)
+ raw_value = raw_value.to_s
+ .gsub(thousands_separator, '')
+ .gsub(decimal_mark, '.')
+ .gsub(/[\s_]/, '')
end
super(record, attr, raw_value)
end
View
12 spec/active_record/monetizable_spec.rb
@@ -105,6 +105,18 @@ class Sub < Product; end
@product.errors[:price_in_a_range].first.should match(/Must be greater than zero and less than \$10k/)
end
+ it "passes validation when amount contains spaces (99 999 999.99)" do
+ @product.price = "99 999 999.99"
+ @product.should be_valid
+ @product.price_cents.should == 9999999999
+ end
+
+ it "passes validation when amount contains underscores (99_999_999.99)" do
+ @product.price = "99_999_999.99"
+ @product.should be_valid
+ @product.price_cents.should == 9999999999
+ end
+
it "passes validation if money value has correct format" do
@product.price = "12,230.24"
@product.save.should be_true

0 comments on commit 73b35b2

Please sign in to comment.
Something went wrong with that request. Please try again.