JavaScript Form
Validation
We?re all familiar with ColdFusion?s built-in <cfform>.
Some people think it?s great, as it automatically generates client side form
validation. Saves you some time, as you no longer need to worry about learning
JavaScript.
While that may be true, there are a number of compelling reasons to not use
<cfform>
1) Every component of cfform (cfinput, cfselect) will slow down the loading of
your page. ColdFusion has to parse each cfform component and convert it into
?regular? HTML, along with any JavaScript validation routines necessary.
2) The validation that you can do with cfform is somewhat limited. For example,
you can determine whether or not a text input is empty?but you could not, for
example, ensure that the length of the value entered was greater than 6
characters (some sites require a password be entered, with a minimum of 6
characters). Writing your own JavaScript will allow you much more flexibility in
the validation that you can perform.
3) <cfform> components such as
<cfinput type=?text?>
are parsed into <input type=?text?>
by the ColdFusion server. However, if you are writing XHTML compliant code
(which you should be), you know that tags such as <input
type=?text?>
become self-closing (e.g. <input type=?text?
/>). <cfform> elements will not do this, and
thus render your entire document as invalid markup.
I?ve always tried to dissuade people from using cfform and learning to write
their own JavaScript. Aside from the reasons above, learning a new technology
will never hurt you. Additionally, since both JavaScript and
<cfscript> (as well as Flash?s ActionScript) are
ECMAScript based, they share many similar properties. Learning JavaScript will
make learning both <cfscript> and ActionScript much
easier.
Certainly, JavaScript can be used for much more than form validation. However,
this is where most people start learning it?and will allow you to start using it
fairly quickly.
An Overview of JavaScript Syntax
1) All of the elements on a Web page are considered to be individual objects to
JavaScript. Objects are referenced using a hierarchical dot-notation. The
topmost object is the window. Within the window is the document. Within the
document there may be a form, and within that form there is likely a form field.
Assuming the form?s name is ?myForm?, and the form field name is ?myField?, the
syntax to access the value of the form field would be:
window.document.myForm.myField.value
Notice that we go from the topmost object, down to the innermost object. ?value?
is obviously not an object, but a property of the innermost object that we
referenced, which was the form field myField.
2) JavaScript is cAsE-sEnSiTiVe. This means if your form is named ?myForm?, you
cannot reference it with window.document.myform? This will throw an error, as
the form ?myform? does not exist.
This will likely be the biggest challenge you face in moving from ColdFusion to
JS.
3) JavaScript has functions, which can simply be thought of as code snippets,
that can be called on a particular event (onmouseover, onclick, onfocus, onblur,
etc).
Here?s a quick sample of a very simple JavaScript function, which is called on
the onload event (the onload event fires when a page finishes loading).
1. <html>
2. <head>
3. <title>Simple JavaScript Example</title>
4. <script language=?JavaScript?
type=?text/javascript?>
5. function sayHi() {
6. alert(?Hello! Welcome to my World!?);
7. }
8. </script>
9. </head>
10.
11. <body onload=?sayHi();?>
12.
13. </body>
14. </html>
What we have here is a simple Web page that will pop up a JavaScript alert box
with the text ?Welcome to my World!? when the page loads.
On lines 5-7, we have our function, which is named sayHi. As with ColdFusion,
functions are followed by parentheses, in order to accommodate any arguments (if
they exist).
The function itself is enclosed in curly braces. This is a simple one line
function, which uses the built in JavaScript alert(). Notice that the line ends
with a semi-colon. While it is not mandatory in JavaScript to terminate a line
with a semi-colon, it is recommended, as it is proper syntax to do so.
<cfscript> adheres to this as well, but is much
more strict (<cfscript> will throw an error if a
line is not properly terminated?JavaScript will not).
On line 11, we have our <body> tag. Within the
<body> tag, we utilize the onload event to call our
function. Again, notice the case-sensitivity. The name of the function is sayHi.
We call it by using sayHi. Not sayhi, Sayhi, or SayHi.
Form Validation
Let?s build a very simple form to start off with.
<form name=?myForm?
method=?post? action=?page2.cfm?>
<input type=?text?
name=?yourName?
/>
<input type=?submit?
value=?proceed? />
</form>
Nothing too fancy. One simple text input, and a submit button. The only thing to
note is that we gave our form a name, using the name attribute of the
<form> tag.

When the user hits the ?proceed? button, the form will submit, whether the user
has entered a value or not.
To prevent that from happening, let?s write our first JavaScript function.
<script language=?JavaScript?
type=?text/javascript?>
function validateFields() {
if (document.myForm.yourName.value ==
??) {
alert(?Please
Enter Your Name?);
}
}
</script>
Our function (named validateFields) is enclosed in curly braces. Within the
function, we have a condition. This condition references our form field (notice
we don?t specify window before we specify document?specifying window is
generally implicit, as all documents are assumed to be within a window?you can?t
be viewing a Web page without it being in a window).
document.myForm.yourName.value is whatever value the user has entered into the
form field.
We use the equality comparison operator, which in JS is == (two equal signs).
This is used to test for equality, where a single equal sign is used to assign
values.
For example:
var myName = ?CJ?; (assignment)
if (myName == ?CJ?) ? (testing for equality)
So our condition checks to see if the value in the specified form field is blank
(an empty string, indicated by ??). If the condition is met, we alert the user
with a JavaScript alert() containing the message ?Please Enter Your Name?.
Now that we have a function, we need to call it on a specific event. JavaScript
has an onsubmit event that pertains to a form. This is the event that we will
use to call our validation function.
<form name=?myForm?
method=?post?
action=?page2.cfm?
onsubmit=?return validateFields();?>
You may be noticing that not only are we calling the function from the onsubmit
event?but we also have the word return before the name of the function. This
indicates that we expect the function to return a value. In this case, we will
return either true or false. A false return value will indicate that the
validation criteria have not been met, and the form will not submit. A true
return value will indicate that all form fields have been successfully
validated, and allow the form to submit.
In order to return a value, we need to make two modifications to our function:
<script language=?JavaScript?
type=?text/javascript?>
function validateFields() {
if (document.myForm.yourName.value == ??) {
alert(?Please Enter Your Name?);
return false;
}
return true;
}
</script>
Notice that within our condition, if the value of the form field is empty, we
not only alert the user, but we also return false. This will prevent the form
from submitting.
If the condition is not met, we return true, which allows the form to submit.
Here is the final product:
<html>
<head>
<title>My First Form Validation</title>
<script language=?JavaScript?
type=?text/javascript?>
function validateFields() {
if (document.myForm.yourName.value == ??) {
alert(?Please Enter Your Name?);
return false;
}
return true;
}
</script>
</head>
<body>
<form name=?myForm?
method=?post?
action=?page2.cfm?
onsubmit=?return validateFields();?>
<input type=?text?
name=?yourName? />
<input type=?submit?
value=?proceed? />
</form>
</body>
</html>
Incidentally, for forms with multiple fields (as most have), you simply put a
condition for each form field in the same function. For example, if our example
above contained a 2nd input, with a name of ?pword? (<input
type=?text? name=?pword?
/>), our function would look like:
<script language=?JavaScript?
type=?text/javascript?>
function validateFields() {
if (document.myForm.yourName.value ==
??) {
alert(?Please
Enter Your Name?);
return false;
}
if (document.myForm.pword.value == ??)
{
alert(?Please
Enter Your Password?);
return false;
}
return true;
}
</script>
As each condition is processed, if the validation criteria is met, the function
simply moves on to the next condition. If the validation criteria is NOT met,
the return false will cease processing of the function immediately.
Copy and paste this into an HTML page and you can test it out yourself. You have
now successfully written your first JavaScript form field validation! Take a
breath, do a victory lap?whatever feels right?and c?mon back so we can tackle a
few other validations that you can add to your form. Some may be a bit more
difficult than the example above?take your time, don?t get discouraged, and ask
questions if you get confused! :)
Validating Text Inputs
All of the examples below will assume one form field (input type=?text?) named
?myField? within a form named ?myForm?.
1) Ensuring at least 3 characters in a field:
if (document.myForm.myField.value.length < 3) {
alert(?Not Enough Characters!?);
return false;
}
As in the previous example, we use hierarchical notation to ?drill down? to the
form field?s value. However, now we are going to access a specific property of
that value. The property in question is ?length? (which is simply appended still
using dot notation).
So our condition states, ?if the length of the value of the field ?myField? in
the form ?myForm? is less than 3 characters, validation fails (alert the user
and return false).?
2) Ensuring no more than 6 characters in a field:
if (document.myForm.myField.value.length > 6) {
alert(?Too Many Characters!?);
return false;
}
Same as above, except now testing for greater than (>) as opposed to less than
(<).
3) Ensuring a length between 3 and 6 characters:
if ((document.myForm.myField.value.length < 3) || (document.myForm.myField.value.length
> 6)) {
alert(?Please enter a value between 3 and 6 characters?);
return false;
}
We are now testing for two distinct criteria. The length must NOT be less than
3, nor can it be greater than 6. We use two sets of validation criteria, each in
parentheses. We use the || character in JavaScript to denote ?OR?. So literally,
we are saying ?If the length of the value of the field ?myField? in the form
?myForm? is less than 3 characters OR the length of the value of the field
?myField? in the form ?myForm is greater than 3 characters, validation fails
(alert the user and return false).?
4) Ensuring only a numeric value:
if (isNaN(document.myForm.myField.value)) {
alert(?Please enter a numeric value only!?);
return false;
}
This one is a bit different. Now we are using a built in JavaScript function,
isNaN(). isNaN() stands for ?is not a number?. Like some ColdFusion functions,
it accepts an argument. In this case, it?s the value to be tested?which is the
value of the field named ?myField? in the form ?myForm?. If this value is not
numeric, validation fails.
5) Ensuring that a value contains the ?@? character:
if (document.myForm.myField.value.indexOf(?@?) < 0) {
alert(?Please Enter a Valid E-Mail Address?);
return false;
}
This example uses JavaScript?s indexOf() method. A method is very similar to a
function (it technically is a function within an object?but that?s more than we
need to be concerned with at this point). indexOf is similar to ColdFusion?s
find() function. It simply searches for the occurrence of a substring within a
string. It returns the position (or index) that the character was found.
Remembering that JavaScript starts counting at 0, indexOf will return a number
greater than or equal to 0 if the substring is found. Otherwise, it returns ?1.
So we check to see if the indexOf method returns a value less than 0. If it
does, validation fails.
Validating Select Inputs
How can you make sure a user has selected a value in a
<select> input? Remembering that a <select>
input is made up of various <option> tags, each
option is considered a position (or, more accurately, an index) within the
select. Since JavaScript starts counting at 0, the very first
<option> in a <select>
holds position 0. Whichever option is currently selected can be ascertained with
the selectedIndex property of a select field.
If the first option is selected, document.myForm.mySelect.selectedIndex will
return 0.
If none are selected (possible in a <select> where
multiple is enabled), selectedIndex returns ?1.
Remember? case sensitivity. The property is selectedIndex. NOT SelectedIndex or
selectedindex.
<select name=?autos?>
<option value=??>Please
Select One:</option>
<option value=?acura?>Acura</option>
<option value=?bmw?>BMW</option>
<option value=?cadillac?>Cadillac</option>
<option value=?lexus?>Lexus</option>
</select>
Given the <select> input above, we want to ensure
that the user has chosen an option other than the first one?which means we
simply want to ensure that the selectedIndex is greater than 0.
if (document.myForm.autos.selectedIndex <= 0) {
alert(?Please Select an Auto?);
return false;
}
Validating Radio Buttons
Radio buttons are groups where only one of the presented choices can be
selected:
The code to generate this group of radio buttons is:
<input type="radio"
name="sex" value="M">Male
<input type="radio"
name="sex" value="F">Female
Notice that the name of both radio buttons is the same (although the values
differ). This is how we ensure that only one input from the group can be chosen.
Radio buttons in JavaScript are slightly more complicated than other inputs.
Because they are comprised of multiple elements with same name, we cannot use
the hierarchical notation that we?re used to. document.myForm.sex.value could
refer to either one of those buttons (and as such, would throw an error). Radio
button groups are actually arrays in JavaScript. Therefore, we must use array
notation to reference a specific radio button. In the case of these two buttons
above, each could be referenced as:
document.myForm.sex[0] (remember, JavaScript starts counting at 0?so this is the
?M? value)
document.myForm.sex[1] (remember, JavaScript starts counting at 0?so this is the
?F? value)
Radio buttons possess a ?checked? property that is either true or false,
depending on the state of the button. In order to ensure that the user has
checked one of the radio buttons within the group, it becomes necessary to loop
over the group:
1. var howMany = 0;
2.
3. for (var i=0; i<document.myForm.sex.length; i++) {
4. if (document.myForm.sex[i].checked == true) {
5. howMany++;
6. break;
7. }
8. }
9.
10. if (howMany == 0) {
11. alert(?Please Indicate Your Sex?);
12. return false;
13. }
Now, I know what you?re saying. ?Whoa?CJ?you went and got funky on me.? Well
yes, admittedly, it?s a little funky. But that?s ok?we can de-funk it easily
enough.
Line 1: sets a variable called howMany, with an initial value of 0. This will
ultimately be the number of checked radio buttons.
Line 3: This is a loop in JavaScript. It?s very similar to a loop in
<cfscript>, and not terribly different than a loop
in CF once it?s been dissected.
We start with a loop index of i. i starts off as 0 (var i=0), and increases by
one for each iteration of the loop (i++). The loop will continue to iterate
while i is less than the length of the radio button array. Since this particular
radio button array only has two items (male or female), the loop will iterate
twice.
Line 4: Uses array notation to check a specific radio button within the group.
Specifically, it is looking to see if that specific radio button is checked. If
it is, proceed to line 5.
Line 5: Use the JavaScript notation to increment a value (the double plus sign)
to increment the value of the variable howMany.
Line 6: Because we have encountered a checked button, which was our goal, there
is no reason to continue looping through the remainder of the buttons. We can
simply break out of the loop.
Line 10: Once the loop is finished (whether it looped over each element, or was
broken out of), check the value of the variable howMany. If it still equals 0,
no radio buttons have been checked. If this is the case, validation fails.
Proceed to line 11.
Line 11: Validation failed. Send an alert() message to the user, and return
false on Line 12.
This might take some going over to get used to, but once you understand the
concept of the radio button group being an array, and looping over the elements
in the array, it will be very clear.
Well, I?m going to leave you there. It?s a lot of new information to take in in
one sitting. Hopefully you feel that you have a better familiarity with
JavaScript and form field validation?and you?ll pursue it to the point where you
can start writing your own validation routines.
To see one single form that holds all of the examples above, please visit
http://charlie.griefer.com/code/js/js_validation.cfm. View the source for a full
understanding.
I would like to suggest a few other resources that might help as well:
The JavaScript Bible, by Danny Goodman. Mr. Goodman is thought of as *the*
definitive JavaScript authority (and with good reason). This book will teach the
most basic beginner, and remain a valuable reference to the most seasoned JS
pro. It?s not so technical that it?s impossible to understand?yet it?s not
dumbed down to the point where it fails to teach.
http://www.w3schools.com/js/default.asp
This site offers a number of different teachings on a number of different
subjects. I can?t speak for the others, but I?ve found their JS section to be
very helpful.
qForms JavaScript API
Dan Switzer has put together a fantastic JavaScript API for interacting with
forms. While I believe that it?s always beneficial to know how to write your own
code, there?s nothing wrong with saving some time once you know how. Dan?s
qForms are free?easy to work with?and will let you easily manipulate your forms.
Not only for form validation, but dynamic drop downs as well (two or more
related selects). Check it out!
http://www.pengoworks.com/index.cfm?action=get:qforms.
The EasyCFM.com forums! Yes, we?re a CF community, but in our daily dealings
with CF, we have to wander into other areas as well. Whether it be SQL, HTML, XHTML, JavaScript, CSS,
etc?we touch it all. So please feel free to ask your JS related questions! I?ll
do my best to answer as many of them as I can :)
CJ