【发布时间】:2016-04-23 18:40:42
【问题描述】:
我有一个简单的 PHP 页面,正在尝试验证表单输入。
在使用无效数据点击
submit时,我的echo语句中不会返回输入的值
我想将echo 输入为value,以便用户可以理解他们输入的错误。以下是我的代码;
"TEST" . $contactEmail的回声和input value都没有显示$contactEmail
<?php
// define variables and set to empty values
$contactFirstNameErr = $contactEmailErr = $retailerIDErr = "";
$contactFirstName = $contactEmail = $retailerID = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input fields
if (empty($_POST["contactFirstName"])) {
$contactFirstNameErr = "<br>*First Name is required";
} else {
$contactFirstName = test_input($_POST["contactFirstName"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$contactFirstName)) {
$contactFirstNameErr = "<br>*Only letters and white space allowed";
}
}
//Email Field
if (empty($_POST["contactEmail"])) {
$contactEmailErr = "<br>*Email is required";
} else {
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$contactEmailErr = "<br>*Invalid email format";
} else {
$contactEmail = test_input($_POST["contactEmail"]);
}
}
//Option Field
if (empty($_POST["retailerID"])) {
$retailerIDErr = "<br>*Retailer is required";
} else {
$retailerID = test_input($_POST["retailerID"]);
}
}
?>
<!--Begin HTML Form-->
<div class="Form_container">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Contact First Name<span class="required">*</span><span class="formError"><?php echo $contactFirstNameErr;?></span><br> <!--<p class='spacerLine'></p>-->
<input type="text" class="largeInput" name="contactFirstName" value="<?php echo $contactFirstName;?>">
<br><br>
Contact E-mail<span class="required">*</span><span class="formError"> <?php echo $contactEmailErr;?></span><br>
<input type="text" class="largeInput" name="contactEmail" value="<?php echo $contactEmail;?>">
<br><br>
<?php echo "TEST" . $contactEmail;?>
<br><br>
Retailer<span class="required">*</span><span class="formError"><?php echo $retailerIDErr;?></span><br>
<input type="text" class="largeInput" name="retailerID" value="<?php echo $retailerID;?>">
<br><br>
<input type="submit" class="button" name="submit" value="Add Contact">
</form>
</div>
有什么想法吗?我是 PHP 新手,但一直非常严格地遵循 W3 教程。会不会是我的课把东西扔掉了?还是我只是弄乱了一个变量名? 感谢大家的帮助
【问题讨论】:
-
顺便说一句,你对像 José 这样的人有什么看法?
-
看起来
$contactEmail从未设置为初始空字符串以外的值。尝试删除else子句并在所有情况下设置$contactEmail = test_input($_POST["contactEmail"]);。 -
好像 test_input() 函数也没有在任何地方定义?
标签: php validation echo