好的,我想要实现的是一个非常简单的表单验证,如下所示。
但是,一旦我点击提交(如果字段为空或已填写),我会在空白页面上显示所有回显的错误。
“名称必须至少为2个字符名称为requiredemail必须至少3个字符无效,电子邮件不能留空”
到目前为止我的代码:
的index.php
<form method="post" action="confirm.php">
Name:<input type="text" name="name" />
email:<input type="text" name="email" />
DOB:<input type="date" name="dob" />
<input type="submit" value="submit" />
</form>
和
confirm.php
<?php
$name = $_POST['$name'];
$email = $_POST['$email'];
$dob = $_POST['$dob'];
$namelen = strlen($email);
$emaillen = strlen($email);
$max = 255;
$minname = 2;
$minemail = 3;
if($namelen<$minname){
echo"name must be at least 2 characters";
}
elseif($namelen>$max){
echo"name must be less than 255 characters";
}
if(empty($name)){
echo"name is required";
}
else{
continue;
}
if($emaillen<$minemail){
echo"email must be at least 3 characters";
}
elseif($emaillen>$max){
echo"email must be less than 255 characters";
}
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
continue;
}
else{
echo"invalid email";
}
if(empty($email)){
echo"email cannot be left empty";
}
else{
continue;
}
?>
非常感谢帮助,谢谢。
答案 0 :(得分:1)
您的代码中包含以下内容:
$name = $_POST['$name'];
$email = $_POST['$email'];
$dob = $_POST['$dob'];
您基本上是在尝试访问未定义的索引。从密钥名称中删除额外的$
:
$name = $_POST['name'];
$email = $_POST['email'];
$dob = $_POST['dob'];
然后,在下面,你有一些这样的条件:
if(condition == true) {
continue;
} else {
// do something
}
实际上没有必要,您可以将其更改为:
if(!condition) {
// do something
}
此外,最好将错误消息推送到数组($errors
),然后遍历它并显示错误消息。它可能有助于更好地组织代码。
修改后的代码如下所示:
if(!empty($_POST)) {
$name = $_POST['name'];
$email = $_POST['email'];
$dob = $_POST['dob'];
$namelen = strlen($name);
$emaillen = strlen($email);
$max = 255;
$minname = 2;
$minemail = 3;
if($namelen < $minname){
$errors[] = "name must be at least 2 characters";
} elseif($namelen > $max){
$errors[] = "name must be less than 255 characters";
}
if($emaillen < $minemail){
$errors[] = "email must be at least 3 characters";
} elseif($emaillen > $max){
$errors[] = "email must be less than 255 characters";
}
if(empty($name)){
$errors[] = "name is required";
}
if(empty($email)){
$errors[] = "email cannot be left empty";
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errors[] = "invalid email";
}
echo "<ul>";
foreach ($errors as $error) {
echo "<li>$error</li>";
}
echo "</ul>";
}
它仍然可以改进,但是,这应该让你开始!
答案 1 :(得分:0)
在检查第一个和第二个错误后,你没有写任何东西让它停止。
此外,continue
语句中的if
没有意义(请参阅http://php.net/manual/en/control-structures.continue.php)。
最后,该页面为“空白”,因为没有HTML输出,只有文本。您可能希望redirect the user返回到包含错误消息的表单页面。
答案 2 :(得分:0)
$name = $_POST['$name'];
$email = $_POST['$email'];
$dob = $_POST['$dob'];
那是错的,你必须使用
$name = $_POST['name'];
$email = $_POST['email'];
$dob = $_POST['dob'];
此外,您可能想要更改行
$namelen = strlen($email);
到
$namelen = strlen($name);
答案 3 :(得分:0)
检查是否(!空($ _ POST [fieldname])) 然后重定向它在javascript中显示字段为空的警报