我正在尝试仅对字母和短划线验证表单字段(用于名字),但无论我如何实现代码,$ player_name的值仍在设置中。
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["player_name"])) {
$nameErr = "Name is required";
} else {
$player_name = test_input($_POST["player_name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z -]+$/",$player_name)) {
$nameErr = "Only letters and white space allowed";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
表单已使用以下代码实现:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Registration Date: <input type="text" name="date_captured" id="date_captured" value="<?php echo $current_date; ?>">
<br><br>
Name: <input type="text" name="player_name" id="player_name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $date_captured;
echo $player_name;
echo "<br>";
?>
即使&#34;只允许字母和空格&#34;如果设置并显示错误,则仍设置$ player_name的值。
答案 0 :(得分:1)
我使用以下方法修复它:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$fieldTitle = "Player Name";
if (empty($_POST["player_name"])) {
$player_nameErr = $fieldTitle . $requiredErrorText;
} else {
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z -]*$/",test_input($_POST["player_name"]))) {
$player_nameErr = $nameValidationErrorText;
} else {
$player_name = test_input($_POST["player_name"]);
}
}