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, an event occurs that can be caught with the form tag'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>

Of course, when validating a form, we only want the form not to submit if something is wrong. The trick is to return false if there is an error, but otherwise return true. So instead of returning false, we call a validation function, which will specify the result to return.

<form action="Process.html" onsubmit="return validate(this);">

The this Object

Notice that we pass the validate() function the this object. The this object refers to the current object - whatever object (or element) the this keyword appears in. In the case above, the this object refers to the form object. So the entire form object is passed to the validate() function. Note, the function name validate() is arbitrary. The function could be called checkForm() or anything else. Let's take a look at a simple example.

Code Sample:

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

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

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

	return true;
}
</script>
</head>
<body>
<h1>Login Form</h1>
<form method="post" action="Process.html"
			onsubmit="return validate(this);">

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

	<input type="submit" value="Submit">
	<input type="reset" value="Reset Form">
</form>
</body>
</html>
  1. When the user submits the form, the onsubmit event handler captures the event and calls the validate() function, passing in the form object.
  2. The validate() function stores the form object in the form variable.
  3. The values entered into the Username and Password fields are stored in variables (userName and password).
  4. An if condition is used to check if userName is an empty string. If it is, an alert pops up explaining the problem and the function returns false. The function stops processing and the form does not submit.
  5. An if condition is used to check that password is an empty string. If it is, an alert pops up explaining the problem and the function returns false. The function stops processing and the form does not submit.
  6. If neither if condition catches a problem, the function returns true and the form submits.

Cleaner Validation

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

One problem is that the validate() function only checks for one problem at a time. That is, if it finds an 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 type="text/javascript">
function validate(form){
	var userName = form.Username.value;
	var password = form.Password.value;
	var errors = [];

	if (!checkLength(userName)) {
		errors.push("You must enter a username.");
	}

	if (!checkLength(password)) {
		errors.push("You must enter a password.");
	}

	if (errors.length > 0) {
		reportErrors(errors);
		return false;
	}

	return true;
}

function checkLength(text, min, max){
	min = min || 1;
	max = max || 10000;

	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);
}
</script>
</head>
<body>
<h1>Login Form</h1>
<form method="post" action="Process.html"
				onsubmit="return validate(this);">

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

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

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. If the minimum length and maximum length are not passed, defaults of 1 and 10000 are used.
    • 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 this 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 the errors array using the push() method. The push method accepts any value or variable and appends it to the array.
  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 returns false and the form is not submitted.
  5. If no errors are found, the validate() function returns true and the form is submitted.
  6. Notice the use of the default operator in the checkLength() function.

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