1

How to write validation in rails so as to allow the below possible values for price

100 or $100 or 100.00 or $100.00

I have declared price field as Float in my model

My current code looks like :

validates :price,numericality: true

which is not allowing values like 100 to get saved.

tin tin
  • 362
  • 1
  • 7
  • 19
  • 2
    Don't store currency symbols in the database. Store just the number. And decorate when rendering. – Sergio Tulentsev Apr 23 '15 at 12:49
  • 2
    For starters, you should use **Decimals** http://stackoverflow.com/questions/1019939/ruby-on-rails-best-method-of-handling-currency-money – steve klein Apr 23 '15 at 12:49
  • 2
    I'd expect it to save 100 but not $100. If you want the user to be able to include the $ too you're going to have to do some processing of the user's input prior to validation. You'd probably be better off showing the currency symbol in your UI and no allowing the user to input it at all. – Shadwell Apr 23 '15 at 12:50

1 Answers1

4

You can add the format option to your validates method.

validates :price, numericality: true,
          :format => { :with => /^\d{1,6}(\.\d{0,2})?$/ 

This will allow values of up to $999999.99 with an optional decimal place (if the decimal is present, no more than 2 digits must follow.)

But like others already mentioned - it's not the best option to save these values into the database.

I can recommend you the RubyMoney gem for working with currencies.

crispychicken
  • 2,592
  • 2
  • 33
  • 50
  • 1
    Regex which includes optional leading $ and optional comma separators: `^\$?[0-9]{1,3}(?:,?[0-9]{3})*(?:\.[0-9]{2})?$` – steve klein Apr 23 '15 at 12:57