我正在制作一个将发送电子邮件的联系表格,但我无法确保人们确实在输入数据(我知道我需要进行更深入的验证,但我想确保它首先工作)。当用户单击发送时,javascript 将检查以确保字段已填写。如果是这样,那么它将在服务器端再次验证,然后发送消息(这工作正常),如果不是,它将显示警报并且它不应该发送消息。
但是,使用此 javascript,如果字段为空,它将显示错误消息,然后仍然发送电子邮件。我在这里做错了什么?
<script type="text/javascript">
function validate() {
var x=document.forms['mailcontact']['name'].value;
var y=document.forms['mailcontact']['email'].value;
var z=document.forms['mailcontact']['subject'].value;
if (x == '' || x == null || x == ' name') {
alert("You need to enter a name");
}
else if (y == '' || y == null || y == ' email') {
alert("You need to enter your email");
}
else if (z == '' || z == null || z == ' subject') {
alert("You need to enter a subject line");
}
else {
document.forms['maincontact'].submit();
}
}
</script>
<form method="POST" action="mail.php" id="mailcontact">
<input value=" name" size="25" id="contactname" type="text" name="name" onblur="if(this.value=='') this.value=' name';" onfocus="if(this.value==' name') this.value='';" />
<input value=" email" size="25" id="contactemail" type="text" name="email" onblur="if(this.value=='') this.value=' email';" onfocus="if(this.value==' email') this.value='';" />
<input value=" subject" size="25" id="contactsubject" type="text" name="subject" onblur="if(this.value=='') this.value=' subject';" onfocus="if(this.value==' subject') this.value='';" />
<textarea name="message"> message</textarea>
<input onclick="validate()" value="validate_then_send" type="image" src="../images/sendbutton.png" style=" width: 200px; border: none; position: relative; left: 360px;" />
</form>