2013-10-16 46 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"]); 
    } 
} 

?>