This question is asked many times. And I reviewed most of them and the problem in all the cases was.
They were not writing return before function call onSubmit form.
They were using onClick instead of onSubmit.
They were returning false inside if statement, so if the if is not true so function returning true and form is submitting.
But my case different from all the above cases.
HTML:
<form id="form-box" name="booksUpload" action="action_page.php" onSubmit="return validateForm()">
/*Various input fields.*/
</form>
JavaScript:
<script>
function validateForm(){
/*Validating phone numner*/
var phone = document.forms["booksUpload"]["phone-number"].value;
var phErr = document.getElementById("phError");
if(phone.toString().length != 10){
phErr.innerHTML = "Enter a valid mobile number (10 digits)";
}
else{
phErr.innerHTML = "";
}
/*Validating Status*/
var status = document.forms["booksUpload"]["status"];
var checked = false;
var statusErr = document.getElementById("statusError");
for(var i = 0; i < status.length; i++){
if(status[i].checked){
checked = true;
break;
}
}
if(checked == false){
statusErr.innerHTML = "Select one option \"Old or New\"";
}
else{
statusErr.innerHTML = "";
}
return false;
}
</script>
You should prevent form submission before calling your function
onsubmit="event.preventDefault(); validateForm();"
I think your submit function is correct ! Just try by writing full html for your function requirement element or id !!!
<form id="form-box" name="booksUpload" action="action_page.php" onSubmit="return validateForm()">
<input type="text" name="phone-number">
<select name="status"></select>
<input type="submit">
</form>
<p id="phError"></p>
<p id="statusError"></p>
function execution is not reaching till return statement, as something wrong within other statements before return. When everything works good in function so return` statement will execute and return false and form will not submit
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With