JavaScript Form Validation
JavaScript Form Validation
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.
document.bgColor = bgColor;
alert(userName + ", the background color is " + bgColor + ".");
}
</script>
</head>
<body>
<h1>Change Background Color</h1>
<form name="BgForm">
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.
In this exercise, you will write a function that bases the value of one text field on the
value of another.
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.
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.
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);">
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.
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 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);">
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.
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>
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>
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;
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.
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 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>