0

Hi I have a ruby regex I made usinig Rubular http://rubular.com/r/RRc8twB6NL which is meant to check for a decimal 10.00 for pricing. I get it to work on Rubular, but in my application this code does not work:

validates_format_of :price, :with=>/^([0-9]{1,}\.{0,}[0-9]{0,2})$/

Thanks for any help

2
  • Your regular expression (which could be rewritten as /^\d+\.*\d?\d?/) matches any string consisting of 3 or more digits and any string consisting of 1 or more digits, then some dots and then 0 to 2 digits (any string containing such a line, in fact). This includes "0007", "0...." and other non-prices. What do you really want to validate? Commented Aug 27, 2011 at 1:36
  • @undur_gongor I just wanted to validate that it would be in format of a price such as $1.00, $10.00, $200.00, etc. Commented Aug 30, 2011 at 1:59

2 Answers 2

1

In case you only want to have prices with one digit and then zeros you need the regex

/\A[1-9]0*\.\d\d\z/

If any number is allowed before the decimal dot it is

/\A[1-9]\d*\.\d\d\z/

If the fraction part is optional it is either of

/\A[1-9]0*(\.\d\d)?\z/
/\A[1-9]\d*(\.\d\d)?\z/

If you want to allow for the dollar sign (maybe with spaces in between) it is either of

/\A(\$\s*)?[1-9]0*\.\d\d\z/
/\A(\$\s*)?[1-9]\d*\.\d\d\z/
/\A(\$\s*)?[1-9]0*(\.\d\d)?\z/
/\A(\$\s*)?[1-9]\d*(\.\d\d)?\z/
Sign up to request clarification or add additional context in comments.

Comments

0

To check for 10.00:

/^10\.00$/

To check for 10.00 - 99.99:

/^[1-9]\d\.\d{2}$/

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.