我正在制作一封发送电子邮件的联系表格,但我确实无法确保人们真正输入数据(我知道我需要进行更深入的验证,但我想确保它有效第一)。当用户点击发送时,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>
答案 0 :(得分:0)
<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();return false;" value="validate_then_send" type="image" src="../images/sendbutton.png" style=" width: 200px; border: none; position: relative; left: 360px;" />
</form>