mrooneyafdo
asked on
PHP form textbox validation
I have a textbox on an order page. The user enters the quantity of the item that they want to buy, and then clicks an order button. What I want is a way to detect if it is an integer and at least 1.
$ValidInt = 0;
if ($quant > 0) // I was hoping any string would not pass this, though I think I am incorrect.
{
if (is_int($quant))
{
$ValidInt = 1;
}
}
That was my original attempt, but it does not seem to work. If the user enters a string or any combination of letters and numbers, then of course $ValidInt should remain 0. If it is a decimal, it should also remain zero. Finally, it must be at least 1. That is what I tried to accomplish, in a few different ways, the above seemed to be my best effort. Thanks!
$ValidInt = 0;
if ($quant > 0) // I was hoping any string would not pass this, though I think I am incorrect.
{
if (is_int($quant))
{
$ValidInt = 1;
}
}
That was my original attempt, but it does not seem to work. If the user enters a string or any combination of letters and numbers, then of course $ValidInt should remain 0. If it is a decimal, it should also remain zero. Finally, it must be at least 1. That is what I tried to accomplish, in a few different ways, the above seemed to be my best effort. Thanks!
ASKER
Well that is probably a much better representation of my code, but something else is still needed. That says it is invalid all the time. I think that is_int() returns false because the value in textbox is passed via the url like addtocart.php?quantity=2, so I am not sure if that automatically makes it a string or something. Whatever that does, it makes is_int() return False even for actual integers. What do I need to do?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Good enough indeed!
you can also use gettype() function
why dont you do test if it is an integer first
if (is_int($quant) && ($quant>0))
{
$validInt=1;
}