繁体   English   中英

功能未验证

[英]Function not validating

我创建了一个简单的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>

因为要在值小于100时出错,而在值大于或等于100时运行函数,请使用<如果值小于100,则将设置error变量,否则将运行函数。 在if语句中,您也不需要括号中的$ _POST [“ amount”],除非当然有多个条件。

另外,在旁注中,缩进代码很有帮助,因此您可以轻松阅读。

<?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"]);
    }
}

?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM