100% found this document useful (1 vote)
458 views16 pages

JavaScript Form Validation

This document discusses JavaScript form validation. It covers accessing form data, validating different form elements like text fields and passwords, and writing clean reusable validation functions. It provides code samples to validate a login form, access form values, validate based on one field populating another, and report all validation errors at once rather than one at a time. The goal is to write validation code that is modular, reusable and provides a clear user experience when errors occur.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
Download as doc, pdf, or txt
100% found this document useful (1 vote)
458 views16 pages

JavaScript Form Validation

This document discusses JavaScript form validation. It covers accessing form data, validating different form elements like text fields and passwords, and writing clean reusable validation functions. It provides code samples to validate a login form, access form values, validate based on one field populating another, and report all validation errors at once rather than one at a time. The goal is to write validation code that is modular, reusable and provides a clear user experience when errors occur.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1/ 16

JavaScript Form Validation

In this lesson of the JavaScript tutorial, you will learn...

1. To access data entered by users in forms.


2. To validate text fields and passwords.
3. To validate radio buttons.
4. To validate checkboxes.
5. To validate select menus.
6. To validate textareas.
7. To write clean, reusable validation functions.
8. To catch focus, blur, and change events.

Accessing Form Data


All forms on a web page are stored in the document.forms[] array. The first form on a
page is document.forms[0], the second form is document.forms[1], and so on. However,
it is usually easier to give the forms names (with the name attribute) and refer to them
that way. For example, a form named LoginForm can be referenced as
document.LoginForm. The major advantage of naming forms is that the forms can be
repositioned on the page without affecting the JavaScript.

Elements within a form are properties of that form and are referenced as follows:

Syntax
document.FormName.ElementName

Text fields and passwords have a value property that holds the text value of the field. The
following example shows how JavaScript can access user-entered text.

Code Sample: FormValidation/Demos/FormFields.html


<html>
<head>
<title>Form Fields</title>
<script type="text/javascript">
function changeBg(){
var userName = document.forms[0].UserName.value;
var bgColor = document.BgForm.BgColor.value;

document.bgColor = bgColor;
alert(userName + ", the background color is " + bgColor + ".");
}
</script>
</head>
<body>
<h1>Change Background Color</h1>
<form name="BgForm">

Your Name: <input type="text" name="UserName" size="10"><br/>


Background Color: <input type="text" name="BgColor" size="10"><br/>

<input type="button" value="Change Background" onclick="changeBg();">


</form>
</body>
</html>
Code Explanation

Some things to notice:

1. When the user clicks on the "Change Background" button, the changeBg()
function is called.
2. The values entered into the UserName and BgColor fields are stored in variables
(userName and bgColor).
3. This form can be referenced as forms[0] or BgForm. The UserName field is
referenced as document.forms[0].UserName.value and the BgColor field is
referenced as document.BgForm.BgColor.value.

Exercise: Textfield to Textfield


Duration: 15 to 25 minutes.

In this exercise, you will write a function that bases the value of one text field on the
value of another.

1. Open FormValidation/Exercises/TextfieldToTextField.html for editing.


2. Write a function called getMonth() that passes the month number entered by the
user to the monthAsString() function in DateUDFs.js and writes the result in the
MonthName field.

Code Sample:
FormValidation/Exercises/TextfieldToTextField.ht
ml
<html>
<head>
<title>Textfield to Textfield</title>
<script src="DateUDFs.js" type="text/javascript"></script>
<script type="text/javascript">
/*
Write a function called getMonth() that passes the
month number entered by the user to the monthAsString()
function in DateUDFs.js and writes the result in
the MonthName field.
*/
</script>
</head>
<body>
<h1>Month Check</h1>
<form name="DateForm">
Month Number: <input type="text" name="MonthNumber" size="2">
<input type="button" value="Get Month" onclick="getMonth();"><br>
Month Name: <input type="text" name="MonthName" size="10">
</form>
</body>
</html>

1. If the user enters a number less than 1 or greater than 12 or a non-number, have
the function write "Bad Number" in the MonthName field.
2. If the user enters a decimal between 1 and 12 (inclusive), strip the decimal portion
of the number.

Where is the solution?

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. Let's take a look at a simple example.

Code Sample: FormValidation/Demos/Login.html


<html>
<head>
<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">
</p>
</form>
</body>
</html>
Code Explanation

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 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 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


<html>
<head>
<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[errors.length] = "You must enter a username.";
}

if (!checkLength(password)) {
errors[errors.length] = "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>
Code Explanation

Some things to notice:

1. Two additional functions are created: checkLength() and reportErrors().


o 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.
o 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.
o 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 returns false and the form is not submitted.
5. If no errors are found, the validate() function returns true and the form is
submitted.

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.

Exercise: Validating a Registration Form


Duration: 25 to 40 minutes.

In this exercise, you will write code to validate a registration form.

1. Open FormValidation/Exercises/FormValidation.js for editing.


o Create a function called compareValues() that takes two arguments: val1
and val2. The function should return:
 0 if the two values are equal
 -1 if val1 is greater than val2
 1 if val2 is greater than val1
o Create a function called checkEmail() that takes one argument: email. The
function should return:
 false if email has fewer than 6 characters
 false if email does not contain an @ symbol
 false if email does not contain a period (.)
 true otherwise
2. Open FormValidation/Exercises/Register.html for editing.
o Add code so that the functions in FormValidation.js are accessible from
this page.
o Create a validate() function that does the following:
 Checks that the FirstName, LastName, City, Country, UserName,
and Password1 fields are filled out.
 Checks that the middle initial is a single character.
 Checks that the state is exactly two characters.
 Checks that the email is a valid email address.
 Checks that the values entered into Password1 and Password2 are
the same.
 If there are errors, passes reportErrors() the errors array and returns
false.
 If there are no errors, returns true.
3. Test your solution in a browser.

In FormValidation/Exercises/FormValidation.js, modify the checkEmail() function so


that it also checks to see that the final period (.) is after the final @ symbol. The solution
is included in FormValidation/Solutions/FormValidation.js.

Where is the solution?

Validating Radio Buttons


Radio buttons that have the same name are grouped as arrays. Generally, the goal in
validating a radio button array is to make sure that the user has checked one of the
options. Individual radio buttons have the checked property, which is true if the button is
checked and false if it is not. The example below shows a simple function for checking
radio button arrays.
Code Sample:
FormValidation/Demos/RadioArrays.html
<html>
<head>
<title>Radio Arrays</title>
<script type="text/javascript">
function validate(form){
var errors = [];

if ( !checkRadioArray(form.container) ) {
errors[errors.length] = "You must choose a cup or cone.";
}

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

return true;
}

function checkRadioArray(radioButtons){
for (var i=0; i < radioButtons.length; i++) {
if (radioButtons[i].checked) {
return true;
}
}
return false;
}

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>Ice Cream Form</h1>
<form method="post" action="Process.html"
onsubmit="return validate(this);">
<b>Cup or Cone?</b>
<input type="radio" name="container" value="cup"> Cup
<input type="radio" name="container" value="plaincone"> Plain cone
<input type="radio" name="container" value="sugarcone"> Sugar cone
<input type="radio" name="container" value="wafflecone"> Waffle cone
<br/><br/>
<input type="submit" value="Place Order">
</form>
</body>
</html>
Code Explanation

The checkRadioArray() function takes a radio button array as an argument, loops through
each radio button in the array, and returns true as soon as it finds one that is checked.
Since it is only possible for one option to be checked, there is no reason to continue
looking once a checked button has been found. If none of the buttons is checked, the
function returns false.

Validating Checkboxes
Like radio buttons, checkboxes have the checked property, which is true if the button is
checked and false if it is not. However, unlike radio buttons, checkboxes are not stored as
arrays. The example below shows a simple function for checking to make sure a
checkbox is checked.

Code Sample:
FormValidation/Demos/CheckBoxes.html
<html>
<head>
<title>Checkboxes</title>
<script type="text/javascript">
function validate(form){
var errors = [];

if ( !checkCheckBox(form.terms) ) {
errors[errors.length] = "You must agree to the terms.";
}

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

return true;
}

function checkCheckBox(cb){
return cb.checked;
}

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>Ice Cream Form</h1>
<form method="post" action="Process.html" onsubmit="return
validate(this);">
<input type="checkbox" name="terms">
I understand that I'm really not going to get any ice cream.
<br/><br/>
<input type="submit" value="Place Order">
</form>

</body>
</html>

Validating Select Menus


Select menus contain an array of options. The selectedIndex property of a select menu
contains the index of the option that is selected. Often the first option of a select menu is
something meaningless like "Please choose an option..." The checkSelect() function in
the example below makes sure that the first option is not selected.

Code Sample:
FormValidation/Demos/SelectMenus.html
<html>
<head>
<title>Check Boxes</title>
<script type="text/javascript">
function validate(form){
var errors = [];

if ( !checkSelect(form.flavor) ) {
errors[errors.length] = "You must choose a flavor.";
}

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

return true;
}

function checkSelect(select){
return (select.selectedIndex > 0);
}

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>Ice Cream Form</h1>
<form method="post" action="Process.html"
onsubmit="return validate(this);">
<b>Flavor:</b>
<select name="flavor">
<option value="0" selected></option>
<option value="choc">Chocolate</option>
<option value="straw">Strawberry</option>
<option value="van">Vanilla</option>
</select>
<br/><br/>
<input type="submit" value="Place Order">
</form>

</body>
</html>

Focus, Blur, and Change Events


Focus, blur and change events can be used to improve the user experience.

Focus and Blur


Focus and blur events are caught with the onfocus and onblur event handlers. These
events have corresponding focus() and blur() methods. The example below shows

1. how to set focus on a field.


2. how to capture when a user leaves a field.
3. how to prevent focus on a field.

Code Sample:
FormValidation/Demos/FocusAndBlur.html
<html>
<head>
<title>Focus and Blur</title>
<script src="DateUDFs.js" type="text/javascript"></script>
<script type="text/javascript">
function getMonth(){
var elemMonthNumber = document.DateForm.MonthNumber;
var monthNumber = elemMonthNumber.value;

var elemMonthName = document.DateForm.MonthName;


var month = monthAsString(elemMonthNumber.value);

elemMonthName.value = (monthNumber > 0 && monthNumber <=12) ? month :


"Bad Number";
}
</script>
</head>
<body onload="document.DateForm.MonthNumber.focus();">
<h1>Month Check</h1>
<form name="DateForm">
Month Number:
<input type="text" name="MonthNumber" size="2" onblur="getMonth();">
Month Name:
<input type="text" name="MonthName" size="10" onfocus="this.blur();">
</form>
</body>
</html>
Code Explanation

Things to notice:

1. When the document is loaded, the focus() method of the text field element is used
to set focus on the MonthNumber element.
2. When focus leaves the MonthNumber field, the onblur event handler captures the
event and calls the getMonth() function.
3. The onfocus event handler of the MonthName element triggers a call to the blur()
method of this (the MonthName element itself) to prevent the user from focusing
on the MonthName element.

Change
Change events are caught when the value of a text element changes or when the selected
index of a select element changes. The example below shows how to capture a change
event.

Code Sample: FormValidation/Demos/Change.html


<html>
<head>
<title>Change</title>
<script src="DateUDFs.js" type="text/javascript"></script>
<script type="text/javascript">
function getMonth(){
var elemMonthNumber = document.DateForm.MonthNumber;
var i = elemMonthNumber.selectedIndex;
var monthNumber = elemMonthNumber[i].value;

var elemMonthName = document.DateForm.MonthName;


var month = monthAsString(monthNumber);

elemMonthName.value = (i === 0) ? "" : month;


}
</script>
</head>
<body onload="document.DateForm.MonthNumber.focus();">
<h1>Month Check</h1>
<form name="DateForm">
Month Number:
<select name="MonthNumber" onchange="getMonth();">
<option>--Choose--</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select><br>
Month Name: <input type="text" name="MonthName" size="10"
onfocus="this.blur();">
</form>
</body>
</html>
Code Explanation

This is similar to the last example. The only major difference is that MonthNumber is a
select menu instead of a text field and that the getMonth() function is called when a
different option is selected.

Validating Textareas
Textareas can be validated the same way that text fields are by using the checkLength()
function shown earlier. However, because textareas generally allow for many more
characters, it's often difficult for the user to know if he's exceeded the limit. It could be
helpful to let the user know if there's a problem as soon as focus leaves the textarea. The
example below, which contains a more complete form for ordering ice cream, includes a
function that alerts the user if there are too many characters in a textarea.

Code Sample:
FormValidation/Demos/IceCreamForm.html
<html>
<head>
<title>Check Boxes</title>
<script type="text/javascript">
function validate(form){
var errors = [];

if ( !checkRadioArray(form.container) ) {
errors[errors.length] = "You must choose a cup or cone.";
}

if ( !checkCheckBox(form.terms) ) {
errors[errors.length] = "You must agree to the terms.";
}

if ( !checkSelect(form.flavor) ) {
errors[errors.length] = "You must choose a flavor.";
}

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

return true;
}

function checkRadioArray(radioButtons){
for (var i=0; i < radioButtons.length; i++) {
if (radioButtons[i].checked) {
return true;
}
}
return false;
}

function checkCheckBox(cb){
return cb.checked;
}

function checkSelect(select){
return (select.selectedIndex > 0);
}

function checkLength(text, min, max){


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

function checkTextArea(textArea, max){


var numChars, chopped, message;
if (!checkLength(textArea.value, 0, max)) {
numChars = textArea.value.length;
chopped = textArea.value.substr(0, max);
message = 'You typed ' + numChars + ' characters.\n';
message += 'The limit is ' + max + '.';
message += 'Your entry will be shortened to:\n\n' + chopped;
alert(message);
textArea.value = chopped;
}
}

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>Ice Cream Form</h1>
<form method="post" action="Process.html" onsubmit="return
validate(this);">
<p><b>Cup or Cone?</b>
<input type="radio" name="container" value="cup"> Cup
<input type="radio" name="container" value="plaincone"> Plain cone
<input type="radio" name="container" value="sugarcone"> Sugar cone
<input type="radio" name="container" value="wafflecone"> Waffle cone
</p>
<p>
<b>Flavor:</b>
<select name="flavor">
<option value="0" selected></option>
<option value="choc">Chocolate</option>
<option value="straw">Strawberry</option>
<option value="van">Vanilla</option>
</select>
</p>
<p>
<b>Special Requests:</b><br>
<textarea name="requests" cols="40" rows="6" wrap="virtual"
onblur="checkTextArea(this, 100);"></textarea>
</p>
<p>
<input type="checkbox" name="terms">
I understand that I'm really not going to get any ice cream.
</p>
<input type="submit" value="Place Order">
</form>

</body>
</html>

Exercise: Improving the Registration Form


Duration: 15 to 25 minutes.
In this exercise, you will make some improvements to the registration form from the last
exercise.

1. Open FormValidation/Exercises/FormValidation2.js in your editor. You will see


that the functions discussed above have been added: checkRadioArray(),
checkCheckBox(), checkSelect(), and checkTextArea().
2. Open FormValidation/Exercises/Register2.html for editing.
o Notice that the following changes have been made to the form:
 State has been changed from a textfield to a select menu. The first
option is meaningless. The next 51 options are U.S. states. The rest
of the options are Canadian provinces.
 Country has been changed to a radio array.
 A Comments field has been added.
 A Terms checkbox has been added.
o Write code that:
 Checks that a country is selected.
 Checks that the country and state selection are in sync.
 Checks that the terms have been accepted.
o Add an event handler to the Comments textarea that alerts the user if the
comment is too long.
3. Test your solution in a browser.

You might also like