Regular Expressions

I am having a really simple problem with regular expressions and
Rails. I need to validate that input is a number or only digits. I
using this:

validates_format_of :po_box,
:with => /\d*/,
:message => “PO Box must be a number
only. Remove all text.”

however, rails is letting anything be entered. i am getting other
regular expressions like /a/ to work but for some reason not \d* or \d
or [0-9]* or [0-9].

Can anyone help?

Okay I found a validation method that works for this:
validates_numericality_of …to answer my own question. However, i
still don’t understand why my approach above still doesn’t work???


/^[±]?\d+$/ is the expression to check if the format is an


You already answered your question, but for the record, /\d*/ matches
zero or more occurrences of numeric digits, so entering anything
meets the zero criterion. You can use \d+ which requires at least one
digit, but more likely, you want /^\d+$/ which requires everything to
be digits and requires an entry.


/^[0-9]+$/ would work as well.


No problem, we’ve said the same thing. :slight_smile:


John Adams wrote:

/^[0-9]+$/ would work as well.


in Regex the

^ Matches the starting position within the string.
$ Matches the ending position of the string or the position just
before a string-terminating newline.

so /^ABC$/ matches ONLY the string ABC. and therefore
/^\d+$/ requires everything to be digits just like steve said