Home > Software engineering >  Product page item validation PHP
Product page item validation PHP

Time:01-17

I have a product page where the user can select X amount of items from a list of 5 different items.

Before the information can be submitted they must have at least one item in their cart.

This is an example of item 1 in the HTML:

<div  id="item1">
    <input id="qty1" name="qty1"  value="" type="text" placeholder="0" autofocus="autofocus" />
    <button type="button" id="addMac">Add</button>
</div>

And the PHP that I am trying to get to do this looks like this:

}elseif (!filter_var($qty1, FILTER_VALIDATE_INT){
    exit("Error: You have no items in your cart.");
}elseif (!filter_var($qty2, FILTER_VALIDATE_INT){
    exit("Error: You have no items in your cart.");
}elseif (!filter_var($qty3, FILTER_VALIDATE_INT){
    exit("Error: You have no items in your cart.");
}elseif (!filter_var($qty4, FILTER_VALIDATE_INT){
    exit("Error: You have no items in your cart.");
}elseif (!filter_var($qty5, FILTER_VALIDATE_INT){
    exit("Error: You have no items in your cart.");
}

Now the user input needs to be validated as an int, 0 is allowed, but again there must be one item in the cart.

With how it's coded right now, it is requiring that there be at least 1 of EVERY item in the cart which is obviously not going to be what someone actually selects.

How can I adjust this to force the user to select a minimum of 1 item, but no maximum before proceeding to the invoice page?

CodePudding user response:

      <form action="" method="POST">
  <label for="ptoduct1">Product1:</label>
  <input type="number" id="fname" name="pro1"><br><br>
  <label for="ptoduct1">Product2:</label>
  <input type="number" id="fname" name="pro2"><br><br>
  <label for="ptoduct1">Product3:</label>
  <input type="number" id="fname" name="pro3"><br><br>
  <label for="ptoduct1">Product4:</label>
  <input type="number" id="fname" name="pro4"><br><br>
  <label for="ptoduct1">Product5:</label>
  <input type="number" id="fname" name="pro5"><br><br>
  <input type="submit" value="Submit" name="submit" >
  </form>
  <?php
  if(isset($_POST['submit'])){
  $product1=$_POST['pro1'];
  $product2=$_POST['pro2'];
  $product3=$_POST['pro3'];
  $product4=$_POST['pro4'];
  $product5=$_POST['pro5'];
   echo $product1,' ' ,$product2,' ',$product3,' ',$product4,' 
  ',$product4;
  }
 ?>
 <?php
 if(isset($_POST['submit'])){
  if($product1>0 or $product2>0 or $product3 >0 or $product4 >0 or 
   $product5 >0){
   echo 'run';
 }
 }
 ?> 
  •  Tags:  
  • Related