I am making a contact form that will send an email, but I’m having trouble with making sure people actually are entering data (I know I need to put up more in-depth validation but I want to make sure it’s working first). When the user clicks send, javascript will check to make sure the fields are filled out. If so, then it will validate again on the server side and then send the message (this is working fine), if not it will display an alert and it should not send the message.
However with this javascript, if a field is empty it will display the error message and then send the email anyway. What am I doing wrong here?
<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>
1 Answer