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?
thanks,
Wes
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???
Wes
/^[±]?\d+$/ is the expression to check if the format is an
integer…
Wes
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.
HTH
/^[0-9]+$/ would work as well.
-john
No problem, we’ve said the same thing.
–j
John Adams wrote:
/^[0-9]+$/ would work as well.
-john
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