我的输入和选择字段验证有问题。 如果输入为空并单击提交警告“此字段是必需的”。
但是当我填写ClientID输入并且选择框为空时,验证将失败。或者反转,当选择了选择框并且输入为空时。
这里是我的代码:
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$nameErr = $katalogErr = $selectKatalog = "";
$kdn = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["kdn"])) {
$nameErr = "This field is required";
} else {
$kdn = test_input($_POST["kdn"]);
// check if kdn only contains letters, numbers and whitespace
if (!preg_match("/^[a-zA-Z0-9 ]*$/", $kdn)) {
$nameErr = "Only letters, numbers and white space allowed";
}
}
if($_POST["selectKatalog"] == 'default'){
$katalogErr = "This field is required";
}
else {
$selectKatalog = $_POST["selectKatalog"];
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Order a Catalog</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
ClientID: <input type="text" name="kdn">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
Catalog: <select name="selectKatalog">
<option value="default">Bitte wählen:</option>
<option value="Catalog1">Catalog1</option>
<option value="Catalog2">Catalog2</option>
<option value="Catalog3">Catalog3</option>
</select>
<span class="error">* <?php echo $katalogErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $kdn;
echo "<br>";
echo $selectKatalog;
?>
</body>
</html>