如果用户输入无效数据,如何立即在输入字段下显示相应的错误消息。 例如,用户在“名称”字段中输入无效数据,错误消息立即出现在名称字段下。 “电子邮件”和“消息”字段也是如此。 我正在使用下一个 HTML 和 PHP 代码:
SMTPDebug = SMTP::DEBUG_SERVER;
$mail->isSMTP();
$mail->SMTPAuth = true;
$mail->Host = "smtp.gmail.com";
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587;
require_once 'config.php';
$mail->Username = SMTP_USERNAME;
$mail->Password = SMTP_PASSWORD;
$mail->setFrom($emailSanitized, $nameSanitized);
$mail->addAddress("myemail@gmail.com", "myemail");
$mail->Subject = $subject;
$mail->Body = "Name: $nameSanitized\nEmail: $emailSanitized\n\n$messageSanitized";
$mail->send();
header("Location: sent.html");
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}
} else {
echo $emailErr;
echo $nameErr;
echo $messErr;
}
?>
我尝试了不同的文章。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
将 HTML 代码放入
else块中} else { ?> <form method="POST" action="send-email.php"> <input type="text" name="name" id="name" placeholder="Name*" required> <div class="error"><?php echo $nameErr ?></div> <input type="email" name="email" id="email" placeholder="Email*" required> <div class="error"><?php echo $emailErr ?></div> <textarea name="message" id="message" placeholder="Your Message*" required></textarea> <div class="error"><?php echo $messErr ?></div> <button type="submit" name="submit" id="submit" class="button">Start</button> </form> <?php }