gpt4 book ai didi

javascript - PHP 联系表单无需填写所有字段即可提交

转载 作者:行者123 更新时间:2023-11-28 00:57:42 25 4
gpt4 key购买 nike

我有一个 PHP 联系表单,即使字段未填写也能正常工作。直到最近我开始每天收到大量空白电子邮件时,这才成为问题。

如何强制填写表单中的所有字段才能使用提交按钮?

下面是我的 PHP 代码:

    <?php

header("Access-Control-Allow-Origin: *");

$EmailFrom = "myemail";
$EmailTo = "myemail";
$Subject = "subject goes here";
$Email = Trim(stripslashes($_POST['email']));
$Message = Trim(stripslashes($_POST['message']));

// validation
$validationOK=true;
if (!$validationOK) {
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
exit;
}

// prepare email body text
$Body .= "Email: ";
$Body .= $Email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $Message;
$Body .= "\n";

// send email
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom" . "\r\n" );

// redirect to success page
if ($success){
print "<meta http-equiv=\"refresh\" content=\"0;URL=contactthanks.php\">";
}
else{
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
}
?>

这是我的 HTML 标记:

                <!-- CONTACT FORM -->
<div class="span9 contact_form">
<div id="note"></div>
<div id="fields">
<div id="post-ajax" style="display: none;"></div>
<form id="contact-form-face" class="clearfix" action="/php/contactengine.php">
<input type="text" name="email" value="Email" onFocus="if (this.value == 'Email') this.value = '';" onBlur="if (this.value == '') this.value = 'Email';" />
<textarea name="message" onFocus="if (this.value == 'Message') this.value = '';" onBlur="if (this.value == '') this.value = 'Message';">Message</textarea>
<input class="contact_btn" name="submit" type="submit" value="Send Message" />
</form>
</div>
</div>
<!-- //CONTACT FORM -->

最佳答案

我找不到你的字段。但总的来说,HTML5 提供了一种非常方便的方法来使表单字段成为必需的。为此,您可以在表单元素中添加一个 required 属性,例如:

<input type="text" name="txt_name" required />

现代浏览器将在表单提交期间验证字段。为了支持旧版浏览器,您可以使用 JS 验证库进行客户端验证并使用 PHP 条件检查,例如if(!empty($_POST['txt_name'])) 用于服务器端验证。

此外,建议不要使用meta refresh标签进行重定向;使用 header('Location: error.htm'); exit; 例如,改为。


<!-- CONTACT FORM -->
<div class="span9 contact_form">
<div id="note"></div>
<div id="fields">
<div id="post-ajax" style="display: none;"></div>
<form id="contact-form-face" class="clearfix" action="/php/contactengine.php">
<input type="text" name="email" value="Email" onFocus="if (this.value == 'Email') this.value = '';" onBlur="if (this.value == '') this.value = 'Email';" required />
<textarea name="message" onFocus="if (this.value == 'Message') this.value = '';" onBlur="if (this.value == '') this.value = 'Message';" required>Message</textarea>
<input class="contact_btn" name="submit" type="submit" value="Send Message" />
</form>
</div>
</div>
<!-- //CONTACT FORM -->

关于javascript - PHP 联系表单无需填写所有字段即可提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43975458/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com