Javascript Question

Soldato
Joined
22 Nov 2007
Posts
4,360
Hi guys got a small problem with form validation. The following code checks if the email field is empty, if it is gives a message if not I want it to submit the form. The problem is when the field is empty it will display the alert and then go on to submit the form which I don't want.

function validateForm(){
var email= document.getElementById('email').value;
if (email.length==''){
alert("please fill out email");}

else if (email.length>3)
{
document.forms['contact'].submit();
}

}
</script>

FORM CODE

<form name="contact" id='contact' method="post" action='ContactPHP.php'>
Your Email: <input name='email' id='email' type='text' /><br />
Your Email:Message:<br />
<textarea name='message' rows='15' cols='40'>
</textarea><br />
<input type="submit" value="submit" onClick="validateForm()"/>
</form>

Anyone see the problem?
 
If thats the code there are syntax errors and you are checking if email length == '' which is an odd comparison.

When you submit the form, it will hit the javascript and probably fail then post. Even if it does what you want, if there is an issue with the email address it will still post as you are not returning false to prevent it.

You should look for some regex for checking email adresses and just do a simple check along the lines of:

if (email is not validated){
alert("email issue");
return false;
}

This means that if the email address is valid it will just go through the javascript and post as it normally would. The main use of the submit() function of forms within javascript is to allow forms to be submitted from not standard elements. You might use it to do dependent select boxes which submit the form when a select element changes its value.
 
Last edited:
This will get you some basic validation.

Code:
function validateForm(){
	var email = document.getElementById('email').value;
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (filter.test(email)) {
		alert('Pass');
	}
	else {
		alert('Fail');
		return false;		
	}
}
 
Back
Top Bottom