2013-10-16 45 views
0

我創建了一個簡單的php頁面,需要驗證輸入的金額是greater than 100還是必須返回error。我的功能雖然發佈時不會被調用且金額less than 100函數未驗證

<html> 
    <head></head> 
    <title></title> 
    <style> 
     .error {color: #FF0000;} 
    </style> 
    <body> 

     <?php 

     function test_input($data) { 
      $data = trim($data); 
      $data = stripslashes($data); 
      $data = htmlspecialchars($data); 
      return $data; 
     } 

     $amountErr = ""; 
     $amount = ""; 
     if ($_SERVER["REQUEST_METHOD"] == "POST") { 
      if (($_POST["amount"]) > 100) { 
       $amountErr = "Value must be equal or greater than 100"; 
      } else { 
       $amount = test_input($_POST["amount"]); 
      } 
     } 
     ?> 
     <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>"> 
      <p><span class="error">*required field.</span></p> 

      Amount:<input type="text" name="amount"/> 
      <span class="error">*<?php echo $amountErr; ?></span> 

      <input type="submit" value="Pay"/> 
     </form> 

    </body> 
</html> 
+1

@Karl有人想要點。當你幫助這些匿名用戶時感到羞愧,他們只是回答並離開,永遠不會再被看到,直到他們的下一期。 –

回答

0

由於要錯誤,如果值小於100,並運行功能,如果它是大於或等於你應該使用<如果是小於100時,它將設置錯誤變量,否則,它將運行該函數。在if語句中,你也不需要$ _POST [「金額」],除非有多個條件。

此外,在附註中,它有助於很多縮進代碼,以便您可以更輕鬆地閱讀它。

<?php 
function test_input($data) { 
    $data = trim($data); 
    $data = stripslashes($data); 
    $data = htmlspecialchars($data); 
    return $data; 
} 
$amountErr=""; 
$amount=""; 
if ($_SERVER["REQUEST_METHOD"] == "POST") { 
    if ($_POST["amount"] < 100) { 
     $amountErr = "Value must be equal or greater than 100"; 
    } else { 
     $amount = test_input($_POST["amount"]); 
    } 
} 

?>