My HTML page contains a form that has two sections for entering text (section1 and section2) . Because I want to validate user input in each section separately, I created function1 for validating section1 and function2 for validating section2:
var formIsValid = true; // global flag-variable to indicate form is valid
function function1() {
if (at least one field in section 1 has bad data) {
formIsValid = false;
return false;
}
else {
formIsValid = true;
return true;
}
}
// function2 is identical, except that it validates section2
// unlike section1, section 2 only has one input field
The idea is that once the user clicks submit button, the browser will first validate section1, and if the user data is valid, proceed to validating section2. If at some point, the data in one of the fields is bad, then the browser will alert the user and let him enter new values for missing/invalid fields.
Here's my code to do it:
function beginTest() {
document.forms[0].onsubmit = function() {
function1();
if (formIsValid == false) {
function1();
return false; // supposed to prevent refreshing, but it does not
}
function2();
if (formIsValid == false) {
function2();
return false; // again, problem with automatic page reloading
}
}
}
The problem is that whenever an invalid value is detected, the whole page is refreshed and the user has to enter every piece of data over again. My goal is to validate the page with no refreshes. In other words, whatever values entered in input fields in either section MUST remain there if they have been successfully validated.
Q: How do I prevent the browser from refreshing the page during validation?
Please, pure JavaScript only, no JQuery. Thank you!