Basics of Form Validation

Contact Us or call 1-877-932-8228
Basics of Form Validation

Basics of Form Validation

When the user clicks on a submit button or presses the return/enter key while in a form field, an event occurs that can be caught with the form's onsubmit event handler. Unless JavaScript is used to explicitly cancel the submit event, the form will be submitted. The return false; statement explicitly cancels the submit event. For example, the following form will never be submitted:

<form action="Process.html" onsubmit="return false;">
	<!--Code for form fields would go here-->
	<input type="submit" value="Submit Form">
</form>

Note that, for brevity, we here use the onsubmit attribute to listen for the submit event; we'll generally listen for the submit event (and other events) with addEventListener() to keep our JavaScript separate from our HTML markup.

Of course, when validating a form, we only want the form not to submit if something is wrong. We can use the preventDefault() method to stop the form from submitting if the data entered by the user doesn't match what we expect. Let's look at an example

Code Sample:

FormValidation/Demos/Login.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
<script>
function validate(e){
	var userName = document.getElementById("Username").value;
	var password = document.getElementById("Password").value;

	if (userName.length === 0) {
		alert("You must enter a username.");
		e.preventDefault();
		return;
	}

	if (password.length === 0) {
		alert("You must enter a password.");
		e.preventDefault();
		return;
	}
}

window.onload = function() {
	document.getElementById("logInForm").addEventListener("submit", function(e){
    	validate(e);
	});
}
</script>
</head>
<body>
<h1>Login Form</h1>
<form method="post" action="Process.html" id="logInForm">

	Username: <input type="text" name="Username" id="Username" size="10"><br>
	Password: <input type="password" name="password" id="Password" size="10"><br>

	<input type="submit" value="Submit">
	<input type="reset" value="Reset Form">
</form>
</body>
</html>

Code Explanation

  1. When the user submits the form, the addEventListener event handler captures the submit event and calls the validate() function, passing in the event object ("e").
  2. The values entered into the Username and Password fields are stored in variables (userName and password).
  3. An if condition is used to check if userName is an empty string. If it is, an alert pops up explaining the problem and we use preventDefault() to prevent the form from submitting. We use return to halt the function - the function does not check for any additional validation errors.
  4. An if condition is used to check that password is an empty string. If it is, an alert pops up explaining the problem and we use preventDefault() to prevent the form from submitting. We use return to halt the function - the function does not check for any additional validation errors.
  5. If neither if condition catches a problem, then there is no call to preventDefault() and the form submits.

Cleaner Validation

There are a few improvements we can make on the last example.

One problem is that the validation() function only checks for one problem at a time. That is, if it finds and error, it reports it immediately and does not check for additional errors. Why not just tell the user all the mistakes that need to be corrected, so (s)he doesn't have to keep submitting the form to find each subsequent error?

Another problem is that the code is not written in a way that makes it easily reusable. For example, checking for the length of user-entered values is a common thing to do, so it would be nice to have a ready-made function to handle this.

These improvements are made in the example below.

Code Sample:

FormValidation/Demos/Login2.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
<script>
function validate(e){
	var userName = document.getElementById("Username").value;
	var password = document.getElementById("Password").value;
	var errors = [];

	if (!checkLength(userName,1,100)) {
		errors[errors.length] = "You must enter a username.";
	}

	if (!checkLength(password,1,100)) {
		errors[errors.length] = "You must enter a password.";
	}

	if (errors.length > 0) {
		reportErrors(errors);
		e.preventDefault();
	}
}

function checkLength(text, min, max){

	if (text.length < min || text.length > max) {
		return false;
	}
	return true;
}

function reportErrors(errors){
	var msg = "There were some problems...\n";
	var numError;
	for (var i=0; i<errors.length; i++) {
		numError = i + 1;
		msg += "\n" + numError + ". " + errors[i];
	}
	alert(msg);
}

window.onload = function() {
	document.getElementById("logInForm").addEventListener("submit", function(e){
    	validate(e);
	});
}
</script>
</head>
<body>
<h1>Login Form</h1>
<form method="post" action="Process.html" id="logInForm">

	Username: <input type="text" name="Username" id="Username" size="10"><br>
	Password: <input type="password" name="Password" id="Password" size="10"><br>

	<input type="submit" value="Submit">
	<input type="reset" value="Reset Form">
</form>
</body>
</html>

Code Explanation

Some things to notice:

  1. Two additional functions are created: checkLength() and reportErrors().
    • The checkLength() function takes three arguments, the text to examine, the required minimum length, and the required maximum length.
    • The reportErrors() function takes one argument, an array holding the errors. It loops through the errors array creating an error message and then it pops up an alert with a message. The \n is an escape character for a newline.
  2. In the main validate() function, a new array, errors, is created to hold any errors that are found.
  3. userName and password are passed to checkLength() for validation.
    • If errors are found, they are appended to errors.
  4. If there are any errors in errors (i.e., if its length is greater than zero), then errors is passed to reportErrors(), which pops up an alert letting the user know where the errors are. The validate() function then uses e.preventDefault() to prevent the form from submiting.

By modularizing the code in this way, it makes it easy to add new validation functions. In the next examples we will move the reusable validation functions into a separate JavaScript file called FormValidation.js.

Next