When I’m trying to validate the form using Javascript it brings the alerts up as it should but the form gets submitted as nothing happened even though false is returned, the alert work only for the first time I press the submit button. Could some one tell me what am I doing wrong:
Javascript:
function checkForm() {
var name, email, text;
name = document.contact.userName.value;
email = document.contact.email.value;
text = document.contact.textarea.value;
//document.write(name + " " + email + " " + text);
if (name == "" || email =="" || text=="") {
alert("Please fill all fields before submitting!");
return false;
}else if (!looksLikeMail(email)) {
alert("Please enter you real email!");
return false;
}else {
alert("Your feedback was sent, Thank you!");
return true;
}
}
function looksLikeMail(str) {
var lastAtPos = str.lastIndexOf('@');
var lastDotPos = str.lastIndexOf('.');
return ((lastAtPos < lastDotPos) && lastAtPos > 0 && str.indexOf('@@') == -1 && lastDotPos > 2 && (str.length - lastDotPos) > 2);
> }
HTML:
<form name="contact" action="login" method="POST" onsubmit="checkForm()">
<input type="hidden" name="page" value="feedback">
<div data-role="fieldcontain">
<fieldset data-role="controlgroup" data-mini="true">
<label for="textinput1">
Name:
</label>
<input id="name" placeholder="Enter your full name" value="" type="text" name="userName"/>
</fieldset>
</div>
<div data-role="fieldcontain">
<fieldset data-role="controlgroup" data-mini="true">
<label for="textinput2">
Email
</label>
<input id="email" placeholder="Enter your email" value="" type="email" name="email" />
</fieldset>
</div>
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<label for="textarea1">
Feedback
</label>
<textarea id="textarea" placeholder="Enter your text here" name="textarea"></textarea>
</fieldset>
</div>
<input type="submit" data-inline="true" data-theme="b" data-icon="check" data-iconpos="right" value="Submit" />
</form>
Change
<form name="contact" action="login" method="POST" onsubmit="checkForm()">to
<form name="contact" action="login" method="POST" onsubmit="return checkForm()">The
onsubmitwill cancel the submission if your function returns false, but only ifonsubmitwill also return false. So you have to pass the return value fromcheckForm().