validate number syntax
validate number syntax
(OP)
i am trying to validate a price field as any number of numerals (but not required like $.99) followed by a decimal (but no required like $9)followed by 1 or 2 numerals (but not required like $9 or $9.).
i start by removing leading and trailing white space and stripping spaces, commas and $ sign, then check what's left
# should only contain numbers and decimals
$price =~ m/[^0-9\.]/
# should follow the pattern described above.....
$price =~ m/([0-9]+)?(\.{1})?([0-9]{1,2})?/
if the value passes i use sprintf to properly format to 2 decimals.
everything works except when 3 numerals are entered after the decimal it passes.
why doesn't it fail since i include {1,2} in the code?
thanks.
i start by removing leading and trailing white space and stripping spaces, commas and $ sign, then check what's left
CODE
# should only contain numbers and decimals
$price =~ m/[^0-9\.]/
# should follow the pattern described above.....
$price =~ m/([0-9]+)?(\.{1})?([0-9]{1,2})?/
if the value passes i use sprintf to properly format to 2 decimals.
everything works except when 3 numerals are entered after the decimal it passes.
why doesn't it fail since i include {1,2} in the code?
thanks.
RE: validate number syntax
Your question has nothing to do with CGI, it is just plain perl.
Regarding your regular expressions :
CODE
# should only contain numbers and decimals# true if $price contains at least one character that is not a digit or a dot
$price =~ m/[^0-9\.]/
# should follow the pattern described above.....# always true
$price =~ m/([0-9]+)?(\.{1})?([0-9]{1,2})?/
Feherke.
http://free.rootshell.be/~feherke/
RE: validate number syntax
For now, you should realize that, in your first pattern match, $price =~ m/[^0-9\.]/, when the first character in your character class, those inside the square brackets [], is an up carat, it turns the class into a negative. So, instead of looking for anythign that is a 0-9 or a decimal, you are looking for anything that is not one of the chars in your char class.
I have not played with you second pattern match, but, I suspect it will work if you put a $ as the last char in the match. That pins the match to the end of the string you are matching. Like
$price =~ m/([0-9]+)?(\.{1})?([0-9]{1,2})?$/
I would also put an up carat at the beginning to pin down that start of your match with the start of the string. Like,
$price =~ m/^([0-9]+)?(\.{1})?([0-9]{1,2})?$/
Without the $, you are asking if the string has 1 or 2 chars from the character class [0-9]. A string with 3 chars does, in fact 1 and 2 chars from that char class, thus it passes the match expression.
With the $ you are asking if the string has 1 or 2 chars from the character class [0-9] and then ends. A string with 3 chars after the decimal will fail this match.
'hope this helps
If you are new to Tek-Tips, please use descriptive titles, check the FAQs, and beware the evil typo.