I'm trying to submit a HTML form, only when all the fields do not return false in the Javascript code.
My HTML looks like this, for simplicity I have just kept the name and email
<form method="post" action="RegistrationServlet" class="iform"
onsubmit="return sendForm();">
<ul><li><label for="YourName">*Your Name <span id="regNameErr"></span></label>
<input class="itext" type="text" name="YourName" id="YourName" /></li>
<li><br /><label for="YourEmail">*Your Email <span id="regEmailErr"></span></label>
<input class="itext" type="text" name="YourEmail" id="YourEmail" /></li>
<li><input type="submit" value="Submit" class="ibutton" name="SendaMessage"
id="SendaMessage" value="Send a Message!" readonly="readonly" /></li></ul></form>
The Javascript looks like this, again for simplicity I am just checking 2 fields:
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript">
window.sendForm = function() {
if (($("#YourName").val() == "") || ($("#YourName").val().length > 55)) {
$("#YourName").addClass("required");
window.scroll(0, 190);
$("#regNameErr").text("required");
return false;
}
if ($("#YourEmail").val() == "") {
$("#YourEmail").addClass("required");
window.scroll(0, 190);
$("#regEmailErr").text("required");
return false;
}
if (!isEmailValid($("#YourEmail").val())) {
$("#YourEmail").addClass("required");
window.scroll(0, 190);
$("#regEmailErr").text("required");
return false;
}
$("#SendaMessage").val("Please Wait...");
return true;
}
Why is the sendForm() function not repeatedly being called to check that all fields are correct before submitting. Any ideas?
Also I understand that I can add a bounty after 2 days but I am not seeing any button on the editor.
Can you help?
sendForm is called only once per submit - this how it works, and there is no reason to call it multiple times.
If you want to have all your fields checked on submit - you should not return after each check. Instead you should postpone this action until the all fields are verified, and introduce some flag to remember results:
function() {
var formValid = true;
if (($("#YourName").val() == "") || ($("#YourName").val().length > 55)) {
...
formValid = false;
}
if ($("#YourEmail").val() == "") {
...
formValid = false;
}
if (!isEmailValid($("#YourEmail").val())) {
...
formValid = false;
}
if (!formValid) {
return false;
}
$("#SendaMessage").val("Please Wait...");
return true;
}
Side note. Have you considered any jQuery validation plugins for this? Might save you some implementation and maintenance efforts.
Related
One way to stop form submission is to return false from your JavaScript function.
When the submit button is clicked, a validation function is called. I have a case in form validation. If that condition is met I call a function named returnToPreviousPage();
function returnToPreviousPage() {
window.history.back();
}
I am using JavaScript and Dojo Toolkit.
Rather going back to the previous page, it submits the form. How can I abort this submission and return to the previous page?
You can use the return value of the function to prevent the form submission
<form name="myForm" onsubmit="return validateMyForm();">
and function like
<script type="text/javascript">
function validateMyForm()
{
if(check if your conditions are not satisfying)
{
alert("validation failed false");
returnToPreviousPage();
return false;
}
alert("validations passed");
return true;
}
</script>
In case of Chrome 27.0.1453.116 m if above code does not work, please set the event handler's parameter's returnValue field to false to get it to work.
Thanks Sam for sharing information.
EDIT :
Thanks to Vikram for his workaround for if validateMyForm() returns false:
<form onsubmit="event.preventDefault(); validateMyForm();">
where validateMyForm() is a function that returns false if validation fails. The key point is to use the name event. We cannot use for e.g. e.preventDefault()
Use prevent default
Dojo Toolkit
dojo.connect(form, "onsubmit", function(evt) {
evt.preventDefault();
window.history.back();
});
jQuery
$('#form').submit(function (evt) {
evt.preventDefault();
window.history.back();
});
Vanilla JavaScript
if (element.addEventListener) {
element.addEventListener("submit", function(evt) {
evt.preventDefault();
window.history.back();
}, true);
}
else {
element.attachEvent('onsubmit', function(evt){
evt.preventDefault();
window.history.back();
});
}
The following works as of now (tested in Chrome and Firefox):
<form onsubmit="event.preventDefault(); validateMyForm();">
Where validateMyForm() is a function that returns false if validation fails. The key point is to use the name event. We cannot use for e.g. e.preventDefault().
Base on #Vikram Pudi answer, we can also do like this with pure Javascript
<form onsubmit="submitForm(event)">
<input type="text">
<input type="submit">
</form>
<script type="text/javascript">
function submitForm(event){
event.preventDefault();
}
</script>
Just use a simple button instead of a submit button. And call a JavaScript function to handle form submit:
<input type="button" name="submit" value="submit" onclick="submit_form();"/>
Function within a script tag:
function submit_form() {
if (conditions) {
document.forms['myform'].submit();
}
else {
returnToPreviousPage();
}
}
You can also try window.history.forward(-1);
Lots of hard ways to do an easy thing:
<form name="foo" onsubmit="return false">
All your answers gave something to work with.
FINALLY, this worked for me: (if you dont choose at least one checkbox item, it warns and stays in the same page)
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form name="helloForm" action="HelloWorld" method="GET" onsubmit="valthisform();">
<br>
<br><b> MY LIKES </b>
<br>
First Name: <input type="text" name="first_name" required>
<br />
Last Name: <input type="text" name="last_name" required />
<br>
<input type="radio" name="modifyValues" value="uppercase" required="required">Convert to uppercase <br>
<input type="radio" name="modifyValues" value="lowercase" required="required">Convert to lowercase <br>
<input type="radio" name="modifyValues" value="asis" required="required" checked="checked">Do not convert <br>
<br>
<input type="checkbox" name="c1" value="maths" /> Maths
<input type="checkbox" name="c1" value="physics" /> Physics
<input type="checkbox" name="c1" value="chemistry" /> Chemistry
<br>
<button onclick="submit">Submit</button>
<!-- input type="submit" value="submit" / -->
<script>
<!---
function valthisform() {
var checkboxs=document.getElementsByName("c1");
var okay=false;
for(var i=0,l=checkboxs.length;i<l;i++) {
if(checkboxs[i].checked) {
okay=true;
break;
}
}
if (!okay) {
alert("Please check a checkbox");
event.preventDefault();
} else {
}
}
-->
</script>
</form>
</body>
</html>
I would recommend not using onsubmit and instead attaching an event in the script.
var submit = document.getElementById("submitButtonId");
if (submit.addEventListener) {
submit.addEventListener("click", returnToPreviousPage);
} else {
submit.attachEvent("onclick", returnToPreviousPage);
}
Then use preventDefault() (or returnValue = false for older browsers).
function returnToPreviousPage (e) {
e = e || window.event;
// validation code
// if invalid
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
}
Lets say you have a form similar to this
<form action="membersDeleteAllData.html" method="post">
<button type="submit" id="btnLoad" onclick="confirmAction(event);">ERASE ALL DATA</button>
</form>
Here is the javascript for the confirmAction function
<script type="text/javascript">
function confirmAction(e)
{
var confirmation = confirm("Are you sure about this ?") ;
if (!confirmation)
{
e.preventDefault() ;
returnToPreviousPage();
}
return confirmation ;
}
</script>
This one works on Firefox, Chrome, Internet Explorer(edge), Safari, etc.
If that is not the case let me know
E.g if you have submit button on form ,inorder to stop its propogation simply write event.preventDefault(); in the function which is called upon clicking submit button or enter button.
Simply do it....
<form>
<!-- Your Input Elements -->
</form>
and here goes your JQuery
$(document).on('submit', 'form', function(e){
e.preventDefault();
//your code goes here
//100% works
return;
});
Disabling submit button also can help to prevent form submission.
<input style="display:none" type="submit" disabled>
Hemant and Vikram's answers didn't quite work for me outright in Chrome. The event.preventDefault(); script prevented the the page from submitting regardless of passing or failing the validation. Instead, I had to move the event.preventDefault(); into the if statement as follows:
if(check if your conditions are not satisfying)
{
event.preventDefault();
alert("validation failed false");
returnToPreviousPage();
return false;
}
alert("validations passed");
return true;
}
Thanks to Hemant and Vikram for putting me on the right track.
Even though it seems obvious it should be noted that you will also have to then submit your form if the validation is good to go if you block submitting with prevent default. I provided a complete example below of validating doc type and then submitting if its the right doc type.
<h2>Document Upload</h2>
<script>
var CanContinue = false;
function validateMyForm()
{
if(CanContinue == false)
{
alert("You must upload a PDF, PNG, or JPG of your document.");
return false;
}
document.getElementById("myForm").submit();
return true;
}
function getFileNameWithExt(event) {
if (!event || !event.target || !event.target.files || event.target.files.length === 0) {
return;
}
const name = event.target.files[0].name;
const lastDot = name.lastIndexOf('.');
const fileName = name.substring(0, lastDot);
const ext = (name.substring(lastDot + 1)).toUpperCase();
if (ext =="JPG") {
extension.value = "image/jpeg";
CanContinue = true;
} else if (ext =="JPEG") {
extension.value = "image/jpeg";
CanContinue = true;
} else if (ext =="PNG") {
extension.value = "image/png";
CanContinue = true;
} else if (ext =="PDF") {
extension.value = "application/pdf";
CanContinue = true;
} else {
alert("You must upload a PDF, PNG, or JPG of your document.");
CanContinue = false;
}
outputfile.value = fileName;
}
</script>
<form method="post" id="myForm" action="/wheregoing" enctype="multipart/form-data" onsubmit="event.preventDefault(); validateMyForm();">
Please upload a JPG, PNG, or PDF of the front of the document.
<input id='inputfile' type="file" name="dafile" onChange='getFileNameWithExt(event)' required>
<input id='extension' type='hidden' name='ContentType' value="">
<input type="submit">
</form>
One way to stop form submission is to return false from your JavaScript function.
When the submit button is clicked, a validation function is called. I have a case in form validation. If that condition is met I call a function named returnToPreviousPage();
function returnToPreviousPage() {
window.history.back();
}
I am using JavaScript and Dojo Toolkit.
Rather going back to the previous page, it submits the form. How can I abort this submission and return to the previous page?
You can use the return value of the function to prevent the form submission
<form name="myForm" onsubmit="return validateMyForm();">
and function like
<script type="text/javascript">
function validateMyForm()
{
if(check if your conditions are not satisfying)
{
alert("validation failed false");
returnToPreviousPage();
return false;
}
alert("validations passed");
return true;
}
</script>
In case of Chrome 27.0.1453.116 m if above code does not work, please set the event handler's parameter's returnValue field to false to get it to work.
Thanks Sam for sharing information.
EDIT :
Thanks to Vikram for his workaround for if validateMyForm() returns false:
<form onsubmit="event.preventDefault(); validateMyForm();">
where validateMyForm() is a function that returns false if validation fails. The key point is to use the name event. We cannot use for e.g. e.preventDefault()
Use prevent default
Dojo Toolkit
dojo.connect(form, "onsubmit", function(evt) {
evt.preventDefault();
window.history.back();
});
jQuery
$('#form').submit(function (evt) {
evt.preventDefault();
window.history.back();
});
Vanilla JavaScript
if (element.addEventListener) {
element.addEventListener("submit", function(evt) {
evt.preventDefault();
window.history.back();
}, true);
}
else {
element.attachEvent('onsubmit', function(evt){
evt.preventDefault();
window.history.back();
});
}
The following works as of now (tested in Chrome and Firefox):
<form onsubmit="event.preventDefault(); validateMyForm();">
Where validateMyForm() is a function that returns false if validation fails. The key point is to use the name event. We cannot use for e.g. e.preventDefault().
Base on #Vikram Pudi answer, we can also do like this with pure Javascript
<form onsubmit="submitForm(event)">
<input type="text">
<input type="submit">
</form>
<script type="text/javascript">
function submitForm(event){
event.preventDefault();
}
</script>
Just use a simple button instead of a submit button. And call a JavaScript function to handle form submit:
<input type="button" name="submit" value="submit" onclick="submit_form();"/>
Function within a script tag:
function submit_form() {
if (conditions) {
document.forms['myform'].submit();
}
else {
returnToPreviousPage();
}
}
You can also try window.history.forward(-1);
Lots of hard ways to do an easy thing:
<form name="foo" onsubmit="return false">
All your answers gave something to work with.
FINALLY, this worked for me: (if you dont choose at least one checkbox item, it warns and stays in the same page)
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form name="helloForm" action="HelloWorld" method="GET" onsubmit="valthisform();">
<br>
<br><b> MY LIKES </b>
<br>
First Name: <input type="text" name="first_name" required>
<br />
Last Name: <input type="text" name="last_name" required />
<br>
<input type="radio" name="modifyValues" value="uppercase" required="required">Convert to uppercase <br>
<input type="radio" name="modifyValues" value="lowercase" required="required">Convert to lowercase <br>
<input type="radio" name="modifyValues" value="asis" required="required" checked="checked">Do not convert <br>
<br>
<input type="checkbox" name="c1" value="maths" /> Maths
<input type="checkbox" name="c1" value="physics" /> Physics
<input type="checkbox" name="c1" value="chemistry" /> Chemistry
<br>
<button onclick="submit">Submit</button>
<!-- input type="submit" value="submit" / -->
<script>
<!---
function valthisform() {
var checkboxs=document.getElementsByName("c1");
var okay=false;
for(var i=0,l=checkboxs.length;i<l;i++) {
if(checkboxs[i].checked) {
okay=true;
break;
}
}
if (!okay) {
alert("Please check a checkbox");
event.preventDefault();
} else {
}
}
-->
</script>
</form>
</body>
</html>
I would recommend not using onsubmit and instead attaching an event in the script.
var submit = document.getElementById("submitButtonId");
if (submit.addEventListener) {
submit.addEventListener("click", returnToPreviousPage);
} else {
submit.attachEvent("onclick", returnToPreviousPage);
}
Then use preventDefault() (or returnValue = false for older browsers).
function returnToPreviousPage (e) {
e = e || window.event;
// validation code
// if invalid
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
}
Lets say you have a form similar to this
<form action="membersDeleteAllData.html" method="post">
<button type="submit" id="btnLoad" onclick="confirmAction(event);">ERASE ALL DATA</button>
</form>
Here is the javascript for the confirmAction function
<script type="text/javascript">
function confirmAction(e)
{
var confirmation = confirm("Are you sure about this ?") ;
if (!confirmation)
{
e.preventDefault() ;
returnToPreviousPage();
}
return confirmation ;
}
</script>
This one works on Firefox, Chrome, Internet Explorer(edge), Safari, etc.
If that is not the case let me know
E.g if you have submit button on form ,inorder to stop its propogation simply write event.preventDefault(); in the function which is called upon clicking submit button or enter button.
Simply do it....
<form>
<!-- Your Input Elements -->
</form>
and here goes your JQuery
$(document).on('submit', 'form', function(e){
e.preventDefault();
//your code goes here
//100% works
return;
});
Disabling submit button also can help to prevent form submission.
<input style="display:none" type="submit" disabled>
Hemant and Vikram's answers didn't quite work for me outright in Chrome. The event.preventDefault(); script prevented the the page from submitting regardless of passing or failing the validation. Instead, I had to move the event.preventDefault(); into the if statement as follows:
if(check if your conditions are not satisfying)
{
event.preventDefault();
alert("validation failed false");
returnToPreviousPage();
return false;
}
alert("validations passed");
return true;
}
Thanks to Hemant and Vikram for putting me on the right track.
Even though it seems obvious it should be noted that you will also have to then submit your form if the validation is good to go if you block submitting with prevent default. I provided a complete example below of validating doc type and then submitting if its the right doc type.
<h2>Document Upload</h2>
<script>
var CanContinue = false;
function validateMyForm()
{
if(CanContinue == false)
{
alert("You must upload a PDF, PNG, or JPG of your document.");
return false;
}
document.getElementById("myForm").submit();
return true;
}
function getFileNameWithExt(event) {
if (!event || !event.target || !event.target.files || event.target.files.length === 0) {
return;
}
const name = event.target.files[0].name;
const lastDot = name.lastIndexOf('.');
const fileName = name.substring(0, lastDot);
const ext = (name.substring(lastDot + 1)).toUpperCase();
if (ext =="JPG") {
extension.value = "image/jpeg";
CanContinue = true;
} else if (ext =="JPEG") {
extension.value = "image/jpeg";
CanContinue = true;
} else if (ext =="PNG") {
extension.value = "image/png";
CanContinue = true;
} else if (ext =="PDF") {
extension.value = "application/pdf";
CanContinue = true;
} else {
alert("You must upload a PDF, PNG, or JPG of your document.");
CanContinue = false;
}
outputfile.value = fileName;
}
</script>
<form method="post" id="myForm" action="/wheregoing" enctype="multipart/form-data" onsubmit="event.preventDefault(); validateMyForm();">
Please upload a JPG, PNG, or PDF of the front of the document.
<input id='inputfile' type="file" name="dafile" onChange='getFileNameWithExt(event)' required>
<input id='extension' type='hidden' name='ContentType' value="">
<input type="submit">
</form>
I have a form which validates password null/blank or not using onblur. And I use a submit button to submit the form. However the submit button needs to be clicked twice before to work. It does not work on the first click after something has been filled in the password box. Below is the code.
With respect to Jquery, I require solution in pure Javascript.
I have tried onkeyup, but that is not a good solution as it will put strain on system, and server (for ajax).
<!DOCTYPE html>
<html>
<body>
<script>
var error_user_password = false;
function checkpw(){
var user_password = document.forms["joinform"]["user_password"].value;
if (user_password == null || user_password == "") {
text = "Password : Required";
document.getElementById("errormsg4").innerHTML = text;
error_user_password = false;
} else {
document.getElementById("errormsg4").innerHTML = "";
error_user_password = true;
}
}
function submitall() {
checkpw()
if(error_user_password == false) {
return false;
} else {
return true
}
}
</script>
</body>
<form id="joinform" method="post" name="joinform" action="#hello" onsubmit="return submitall()" >
<h2>Join</h2>
<input type="password" name="user_password" id="user_password" placeholder="Password" onblur="checkpw()" />
<div class ="errormsg" id ="errormsg4"></div><br>
<input type="submit" name="join" id="join" value="Submit" ><br><br>
</form>
</html>
OnBlur Validation Requires Onsubmit Button to Be Clicked Twice in Pure Javascript
This happens because the blur event is captured from the onblur event handler and not bubbled to the form submit button.
A full javaScript solution is based on:
addEventListener
activeElement: inside the blur event I check after 10 milliseconds if the submit button get the focus.
My snippet:
var error_user_password = false;
function checkpw(ele, e){
var user_password = document.forms["joinform"]["user_password"].value;
if (user_password == null || user_password == "") {
text = "Password : Required";
document.getElementById("errormsg4").innerHTML = text;
error_user_password = false;
} else {
document.getElementById("errormsg4").innerHTML = "";
error_user_password = true;
}
}
function submitall(ele, e) {
checkpw();
if(error_user_password == false) {
e.preventDefault();
} else {
console.log('form submitted');
}
}
window.addEventListener('DOMContentLoaded', function(e) {
document.getElementById('user_password').addEventListener('blur', function(e) {
checkpw(this, e);
setTimeout(function() {
if (document.activeElement.id == 'join') {
document.activeElement.click();
}
}, 10);
}, false);
document.getElementById('joinform').addEventListener('submit', function(e) {
submitall(this, e);
}, false);
});
<form id="joinform" method="post" name="joinform" action="#hello">
<h2>Join</h2>
<input type="password" name="user_password" id="user_password" placeholder="Password"/>
<div class ="errormsg" id ="errormsg4"></div><br>
<input type="submit" name="join" id="join" value="Submit" ><br><br>
</form>
When i post form only the title validation is working, the other two fields are not validated.
HTML
<form name="qaform" class="nice" method="POST" onsubmit="validateForm()" action="/ask/ask-question/">
<input type="hidden" id="id_selected_tags" name="tags">
<p>
<label for="id_title" class="inline-block">Title</label>
<input type="text" class="input-text inline-block" id="id_title" name="question_title">
</p>
<span id="error_title"></span>
<textarea id="id_question" name="question_description" class="full-width"></textarea>
<span id="error_body"></span>
<p>
<label for="id_tags" class="inline-block">Tags</label>
<input type="text" id="id_newstagbox" name="question_tags"/>
</p>
<span id="error_tags"></span>
<button class="btn btn-success" type="submit">Post your question</button>
</form>
JS
function validateForm()
{
//title validation
if (document.qaform.question_title.value == "") {
document.getElementById('error_title').innerHTML="*Please add a title*";
return false;
}
//body validation
if (document.qaform.question_description.value == "") {
document.getElementById('error_body').innerHTML="*Please add a description*";
return false;
}
//tag validation
if (document.qaform.question_tags.value == "") {
document.getElementById('error_tags').innerHTML="*Please add a description*";
return false;
}
}
After submitting the forms post successfully if title is present.
The stackoverflow form validation forced me to do this, its constantly saying me to add more text because my question contains mostly code.I know its good to provide more information about question but there are times when you can ask a question in few words without being too broad and then you have to rant about it to pass the FORM VALIDATION.
Just remove return false.modify it like below
<script>
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
var y=document.forms["myForm"]["farea"].value;
var z=document.forms["myForm"]["ftag"].value;
if (x==null || x=="")
{
document.getElementById('ern').innerHTML="*Please add a title*";
}
if (y==null || y=="")
{
document.getElementById('era').innerHTML="*Please add a desxription*";
}
if (z==null || z=="")
{
document.getElementById('ert').innerHTML="*Please add a tag*";
}
}
</script>
I prefer using jQuery:
$('#form').submit(function(e) {
var validated = true;
e.preventDefault();
//title validation
if ($('#id_title').val() == "") {
$('#error_title').html("*Please add a title*");
validated = false;
}
//body validation
if ($('#id_question').val() == "") {
$('#error_body').html("*Please add a description*");
validated = false;
}
//tag validation
if ($('#id_newstagbox').val() == "") {
$('#error_tags').html("*Please add a description*");
validated = false;
}
if(validated) {
$(this).unbind('submit').submit();
}
});
You just remove your return false inside each condition,
check this jsfiddle how it works if you remove return false line.
Note:Return false will stop your execution there
Remove the "return false" in the if clauses. This stops your function and the other if clauses wouldn´t get called.
just add 'return' keyword before validateform()
like this
<form name="qaform" class="nice" method="POST" onsubmit="return validateForm()" action="/ask/ask-question/">
Try making these 5 small changes to your validateForm method -
function validateForm() {
var valid = true; // 1
//title validation
if (document.qaform.question_title.value == "") {
document.getElementById('error_title').innerHTML="*Please add a title*";
valid = false; // 2
}
//body validation
if (document.qaform.question_description.value == "") {
document.getElementById('error_body').innerHTML="*Please add a description*";
valid = false; // 3
}
//tag validation
if (document.qaform.question_tags.value == "") {
document.getElementById('error_tags').innerHTML="*Please add a description*";
valid = false; // 4
}
return valid; // 5
}
i think the reason why it only validates the first one, is because you return false to exit the validate function, if you do the return false after all the if loops i think it will do what you want.
I'm trying to make a basic form validation but it's not working. I need to make it in such a way that after validation is passed, THEN ONLY it submits the form. I'm not sure how to do it though. My code is below.
[Important request]
** I'm actually pretty new to this so if possible I would like to get some concrete information/explanation concerning the DOM and how to manipulate it and style it (W3School is NOT helping) **
<form id="reg" method="POST" action="user.php" onsubmit="return validate()">
<label for="first">First Name: </label>
<input id="first" name="first" type="text" value="">
<label for="last">Last Name: </label>
<input id="last" name="last" type="text" value="">
<button type="submit">Register</button>
</form>
function validate(){
if(document.getElementById('first').value == ""){
alert('First Name Blank!');
return false;
}else{
return true;
}
if(document.getElementById('last').value == ""){
alert('Last Name Blank!');
return false;
}else{
return true;
}
}
Thanks
Try this:
function validate() {
var validForm = true;
var msg = '';
if (document.getElementById('first').value == "") {
msg += 'First Name Blank! ';
validForm = false;
}
if (document.getElementById('last').value == "") {
msg += 'Last Name Blank! ';
validForm = false;
}
if (!validForm) {
alert(msg);
}
return validForm;
}
Plunker example
Your validation function only validates the first name. Whether it's valid or not, the function returns before checking the last name.
function validate(){
if(document.getElementById('first').value == ""){
alert('First Name Blank!');
return false; // WILL RETURN EITHER HERE ...
}else{
return true; // ... OR HERE
}
The return statement will exit the function at the point it appears, and other code after that is simply not executed at all.
Instead of doing it that way, keep a flag that determines whether the fields are all OK:
function validate(){
var isValid = true; // Assume it is valid
if(document.getElementById('first').value = ""){
alert('First Name Blank!');
isValid = false;
}
if(document.getElementById('last').value == ""){
alert('Last Name Blank!');
isValid = false;
}
return isValid;
}
Here's the code to check for validation and stop it from submitting if it is incorrect data.
<form id="reg" method="POST" action="user.php">
<label for="first">First Name: </label>
<input id="first" name="first" type="text" value="">
<label for="last">Last Name: </label>
<input id="last" name="last" type="text" value="">
<button type="button" id="submit">Register</button>
</form>
document.getElementById('submit').onclick = function(){
if(validate()){
document.getElementById('reg').submit();
}
}
function validate(){
if(document.getElementById('first').value == ""){
alert('First Name Blank!');
return false;
}else if(document.getElementById('last').value == ""){
alert('Last Name Blank!');
return false;
}else{
return true;
}
}
All I have done here is made the submit button a regular button and handled submitting via JS, When an input of type submit is clicked the page will submit the form no matter what. To bypass this you can make it a regular button and make it manually submit the form if certain conditions are met.
Your javascript code can be:
document.getElementById('submit').onclick = function () {
if (validate()) {
document.getElementById('reg').submit();
}
}
function validate() {
if (document.getElementById('first').value == "") {
alert('First Name Blank!');
return false;
} else if (document.getElementById('last').value == "") {
alert('Last Name Blank!');
return false;
} else {
return true;
}
}