hey well ive done this code to check to see if there is any input, else if (!isset($_POST['item_stock']) || trim($_POST['item_stock']) == "") { echo "<span class=\"red\">Please enter a stock amount,/span>"; } Code (markup): but how can i modify this to check weither the input is 1 - 100 and then echo it is not a integer 1 - 100
I would do it like this: else if (empty($_POST['item_stock']) || !ctype_digit($_POST['item_stock'])) { echo '<span class="red">('.$_POST['item_stock'].') Is not a valid amount. Please enter a valid stock amount between 1 and 100!</span>'; } PHP: As long as you aren't reporting notices, this should cover empty posts and non-numeric posts.
have you tried using the is_numeric() ?? if(is_numeric($_POST['item_stock'])){ print "must be an number right!!"; }else{ print "ahh its not a number!"; }
Unless I'm very much mistaken, none of the solutions above provides a check to see whether the given number is in the interval [1,100]. else if (empty($_POST['item_stock']) || !ctype_digit($_POST['item_stock']) || $_POST['item_stock'] < 1 || $_POST['item_stock'] > 100) { echo '<span class="red">('.$_POST['item_stock'].') Is not a valid amount. Please enter a valid stock amount between 1 and 100!</span>'; } PHP: I believe that might help you.
I prefer to use regex when I check to make sure they entered ONLY numbers. elseif (empty($_POST['item_stock'])) { ?><span class="red">Please enter a stock amount</span><? } elseif(!preg_match("#^[0-9]+$#", $_POST['item_stock']) || $_POST['item_stock'] < 1 || $_POST['item_stock'] > 100) { ?><span class="red">Please enter a number between (and including) 1 - 100</span><? } PHP:
is_int won't work since form input type is always string, not int. is_numeric will also allow things like negatives (which checking if it's below 1 will obviously stop) but it will also allow decimals and exponents. I assume he doesn't want to sell 3.5 items or 4.9e2
Ok, you are right, is_int is not suitable for strings, is_numeric allows floating number/number in exponential form. Anyway I still prefer this construction over the regex (using built-in intval function): $stock = intval(@$_POST['item_stock']); if (!$stock || $stock > 100) echo 'Stock must be a number between [1 - 100]'; PHP:
Yeah that would work but it wouldn't work for checking if the person themselves actually entered in a usable integer. He likes it though so it's fine but in terms of letting things slide, that'd be a big one, since you're letting them enter decimals, but you're just converting them yourself without the person knowing. If you really don't wanna use regex, Perow had the best idea with using ctype_digit() or you could do something like.. if((string)(int)$var != $var){}