我的 Javascript 验证没有激活有问题。我在这个 HTML 表单上也有一个 PHP 邮件程序,一旦按下提交,它就会提交表单并且没有进行验证。
这是 HTML 表单的代码:
<form name="contact" action="mailer.php" onsubmit="return ValidateForm()" method="post"><fieldset>
<tr><td><label for="name">Name:</label></td>
<td><input type="text" name="name" id="name" placeholder="Enter your full name" />
</td></tr>
<tr><td><label for="email">Email:</label></td>
<td><input type="email" name="email" id="email" placeholder="Enter your email address" />
</td></tr>
<tr><td><label for="tel">Phone:</label></td>
<td><input type="tel" name="tel" id="tel" placeholder="Enter your phone number" />
</td></tr>
<tr><td><label for="message">Message:</label></td>
<td><textarea id="message" name="message" placeholder=""></textarea>
</td></tr>
<tr><td><input type="submit" value="Submit" name="submit" />
</form>
这是 PHP 邮件程序的代码:
<?php
if(isset($_POST['submit'])) {
$to = "email@address.com.au";
$subject = "Subject";
$name_field = $_POST['name'];
$email_field = $_POST['email'];
$tel_field = $_POST ['tel'];
$message = $_POST['message'];
$body = "From: $name_field\n E-Mail: $email_field\n Phone: $tel_field\n Message:\n $message";
mail($to, $subject, $body, "From: $email_field");
echo "Data has been submitted to $to!";
echo "<a href='index.html'>Go back to Home Page</a>";
} else {
echo "error";
}
?>
这是验证器的代码:
<script type="text/javascript">
{function validateForm()
{
var x=document.forms["contact"]["name"].value;
if (x==null || x=="")
{
alert("Name field must be filled out");
return false;
}
var x=document.forms["contact"]["email"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
var x=document.forms["contact"]["tel"].value;
if (y==null || y=="")
{
alert("Phone number must be provided");
return false;
}
var x=document.forms["contact"]["message"].value;
if (x==null || x=="")
{
alert("You have not entered a message");
return false;
}
</script>
我曾尝试将 javascript 验证器作为服务器上的单独文件或脚本本身以 html 文档的形式放入,但似乎都不起作用。我做了很多搜索并检查了代码,我很确定它是正确的,但是找不到任何东西来说明这两个功能是否可以一起使用。如果有人可以请确认它会很棒!
任何意见,将不胜感激!
提前致谢!
卡兹