**我正在使用php创建表单应用程序。此代码无法正常运行。我想在它为空时显示错误Student ID is required
。并且该值必须仅包含4位数。不能输入字符串值和特殊字符。以上所有都应该得到验证。如何解决这个问题呢。任何人都可以帮助我。谢谢... !!! **
<!DOCTYPE html>
<html>
<head>
<title> Enter Details </title>
</head>
<body>
<?php
$id = "";
$idErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST"){
if (empty($id)){
$idErr = "Student ID is required";
}elseif(preg_match('/^\d+$/',$_GET['id'])){
$idErr = "Only numbers allowed";
}elseif(strlen($id) != 4) {
$idErr = "Please enter 4 numbers";
}
}
?>
<form action = <?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> method = "post">
Student ID: <input placeholder="Student ID" type = "text" name= "id" value = ""/>
<span class="error">* <?php echo $idErr;?></span></br></br>
<input type = "submit" name = "submit" value = "Register"/>
</form>
</body>
</html>
答案 0 :(得分:2)
您定义一个空变量,如果帖子提交,请检查它是否为空。这将始终为true,因为此变量的空字符串为值。您应该尝试使用$_POST
。您还应将$_GET['id']
更改为$_POST['id']
:
<?php
$idErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$id = $_POST['id'];
if (empty($id)){
$idErr = "Student ID is required";
} elseif(preg_match('/^\d+$/',$_POST['id'])) {
$idErr = "Only numbers allowed";
} elseif(strlen($id) != 4) {
$idErr = "Please enter 4 numbers";
}
}
?>
如果你尝试这个,你应该能得到不同的结果。
答案 1 :(得分:1)
<?php
$id = "";
$idErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$idVal = $_POST['id'];
if (empty($idVal)){
$idErr = "Student ID is required";
}elseif(!is_numeric($idVal)){
$idErr = "Only numbers allowed";
}elseif(strlen($idVal) != 4) {
$idErr = "Please enter 4 numbers";
}
}
?>
//it check like below
empty->number->exact 4 digit-> success.....