2

I have the following validation of product's price:

class Product < ActiveRecord::Base
    ...
    PRICE_REGEX = /^([1-9]\d{0,5}|0)(\.\d{1,2})?$/
    validates :price, :presence => true, :format => PRICE_REGEX
    ...
end

It supposed to allow prices from 0 to 999999.99.

However, if I enter hello, the validation passes, and 0.00 is saved in the database.

The :presence validation works fine, though.

What am I missing here ?

2 Answers 2

5

The price column is a float, and so Rails will automatically convert the string "hello" to float, as per "hello".to_f # => 0.0. This is then converted back to the string "0.0", which obviously matches the regular expression.

In general, it's a bad idea to use regular expressions on non-string columns. Instead, use validates_numericality_of. If you wanted the same restriction as with the regex, do it like this:

class Product < ActiveRecord::Base
  validates_numericality_of :price, :greater_than => 0, :less_than => 1000000
end

Not only is it safer, but it's easier to read and follow as well. Note that it'll automatically reject the price if blank as well.

Sign up to request clarification or add additional context in comments.

Comments

0

I haven't tested this, but every description I saw from validates uses :format in this way:

validates :price, :presence => true, :format => { :with => PRICE_REGEX }

Maybe the problem is there

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.