请检查我的代码。我有2个字段用于验证电子邮件
一个
if ($email == NULL) {
$error['email'] = "email is missing";
}
另一个是
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error['emailfilter'] = "email is Invalid";
}
但我的问题是当电子邮件字段为空/空时。我发现那2个交战是显示的。 “电子邮件丢失”& “电子邮件无效”;我只希望展示一个战争。例如,如果电子邮件提交为空白/空白。它只会显示“电子邮件丢失”没有显示“电子邮件无效”,当电子邮件无效时它将显示“电子邮件无效”。以下是我的完整代码。
<?php
if (isset($_POST['contact'])) {
$warning = array();
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$msg = $_POST['message'];
$to = "asifurrahaman124@gmail.com";
$sub = "you got a msg";
$headers = "from: $email";
if ($firstname == NULL) {
$error['fname'] = "firstname is missing";
}
if($lastname == NULL){
$error['lname'] = "Last name is missing";
}
if ($email == NULL) {
$error['email'] = "email is missing";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error['emailfilter'] = "email is Invalid";
}
if ($msg == NULL) {
$error['msg'] = "message is required";
}
if (count( $error ) == 0) {
mail($to, $sub, $msg, $headers);
$success = "Message Submited";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>conatact</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<form action="" method="POST">
<input type="text" name="firstname" Placeholder="First Name"><br />
<p class="error"><?php if (isset($error['fname'])) {
echo $error['fname'];
}?></p>
<input type="text" name="lastname" Placeholder="Last Name"><br />
<p class="error"><?php if (isset($error['lname'])) {
echo $error['lname'];
}?></p>
<input type="email" name="email" Placeholder="Email"><br />
<p class="error"><?php if (isset($error['email'])) {
echo $error['email'];
}?></p>
<p class="error"><?php if (isset($error['emailfilter'])) {
echo $error['emailfilter'];
}?></p>
<textarea name="message" cols="30" rows="10"></textarea><br />
<p class="error"><?php if (isset($error['msg'])) {
echo $error['msg'];
}?></p>
<input type="password" name="password" Placeholder="Password"><br />
<input type="submit" value="send" name="contact">
</form>
<h2 class="error"><?php if (isset($success)) {
echo $success;
}?></h2>
</body>
</html>
答案 0 :(得分:0)
您希望使用elseif,只有在第一个条件不匹配时才会触发。
if ($email == NULL) {
$error['email'] = "email is missing";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error['emailfilter'] = "email is Invalid";
}
这将检查第一个条件,他们是否有电子邮件,如果没有填写$error['email']
,如果电子邮件有值,那么它将执行电子邮件上的filter_var
以检查这是有效的。