0

I'm using a regex to validate a form field in my sinatra app that's being sent to my db using the data_mapper gem. The code I'm using for the field in my model is:

property :price, Float, :required => true, :format => /\$?\d{0,3}\.{1}\d{2}/

And it's being saved from the params:

b.price = params[:price]

I keep getting an invalid format error when I try to save, though. I checked my regex with rubular and it seems to be working correctly. Anyone have any idea what's going wrong?

Stuart Nelson
  • 4,202
  • 2
  • 23
  • 26

1 Answers1

0

It's not perfect, but here's what I'm currently doing as a solution:

property :price, Float, :required => true 
validates_format_of :price, :with => /\$?\d{0,3}(\.{1}\d{2})?/

And then:

c = params[:price]
c[0] == "$" ? b.price = c[1,7] : b.price = c

So if there's a "$" I'm just saving the number to b.price without it, otherwise the whole thing gets set to b.price. I feel like there should be a better way...

Stuart Nelson
  • 4,202
  • 2
  • 23
  • 26