gpt4 book ai didi

php - 验证 HTML 联系表单

转载 作者:行者123 更新时间:2023-11-28 20:19:58 24 4
gpt4 key购买 nike

我有一个 HTML 联系表单,需要以某种方式进行验证。

如果有任何字段尚未填写,我不会在 JavaScript 中提醒用户,而是更愿意在留空的字段下方显示“必填字段”字样。

这是我的联系表单contact.html:

<form id = "myForm" action="contact.php" method="post">

<label for="name">Name:</label>
<input type="text" name="name" id="name" value="" tabindex="1" />


<label for="name">Email:</label>
<input type="text" name="email" id="email" value="" tabindex="1" />


<input type="submit" value="Submit" class="button" />
</form>

这是我的 PHP 表单 contact.php(除了验证之外的所有内容都被省略):

//Validation... I am building up an error message string to alert the user at the end (omitted) 

$errormessage = '';

if(!isset($_POST['name']) || strlen($_POST['name']) < 1){
$errormessage .= 'You have not entered your Name\n';
}

if(!isset($_POST['email']) || strlen($_POST['email']) < 1){
$errormessage .= 'You have not entered your Email Address\n';
}

if($errormessage != ''){ ?>

<script language="javascript" type="text/javascript">
alert('<?php echo "$errormessage" ?>');
window.location = 'contact.html';
</script>

<?php }


else {

$mail_to = 'info@email.co.uk';
$subject = 'Message from a site visitor '.$field_name;

$body_message = 'From: '.$field_name."\n\n";
$body_message .= 'E-mail: '.$field_email."\n\n";



$headers = 'From: '.$field_email."\r\n";
$headers .= 'Reply-To: '.$field_email."\r\n";

$mail_status = mail($mail_to, $subject, $body_message, $headers);

}

正如您所看到的,我当前的验证在 PHP 中构建了一个字符串,该字符串将在最后向用户发出警报(省略),但是我想通过在 HTML 字段下方显示字符串“Field required”来替换此方法已留空。

最佳答案

如果您可以使用某些 html5 功能,另一个选择是在输入上设置 required 属性。

required

This attribute specifies that the user must fill in a value before submitting a form. It cannot be used when the type attribute is hidden, image, or a button type (submit, reset, or button). The :optional and :required CSS pseudo-classes will be applied to the field as appropriate.

取自 https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input

所以你的 html 将变成:

<form id = "myForm" action="contact.php" method="post">

<label for="name">Name:</label>
<input type="text" name="name" id="name" value="" tabindex="1" required />


<label for="name">Email:</label>
<input type="text" name="email" id="email" value="" tabindex="1" required />


<input type="submit" value="Submit" class="button" />
</form>

关于php - 验证 HTML 联系表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18535392/

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