【发布时间】:2016-01-19 03:33:13
【问题描述】:
我真的是互联网语言的新手,我试图弄清楚如何在方法调用之前验证用户输入,但我还不能让它工作。
<html>
<head>
</head>
<body>
<?php
$grade = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$returned = test_input($_POST["grade"]);
if(!$returned) ?
}
function test_input($data)
{
if ( !is_numeric($data) || $data>100 || $data<0 )
{
$data = "";
echo 'The input should be a number between 0 and 100 ';
echo "<br>";
echo 'Try again';
return false;
}
return true;
}
?>
<form action = "file_1_2.php" method = "post">
Grade: <input type="text" name="grade">
</form>
</body>
</html>
【问题讨论】:
-
你应该把这个
$data>0改成这个$data<0(小于零)。还有这个<form action = "file_1_2.php" method = <"post">到这个<form action = "file_1_2.php" method = "post">(删除错误的<字符)。 -
您要进行哪种类型的验证?
-
您可以使用 jquery 进行验证。这很容易
-
无论如何,您都不应该依赖客户端验证。用户可以将其关闭,则您没有验证。您最好坚持使用服务器端验证,然后在时间允许的情况下添加客户端。
-
另外,让你的函数只返回一个
bool值,不要让它回显任何东西。这样您就可以稍后重用该函数,而不会返回您无法更改的错误值。