User Guide

104 Chapter 8: Lesson 4: Validating Data to Enforce Business Rules
5 View the tripedit.cfm page in a browser. Select the event types drop-down list. Notice that all
seven event types appear in the list.
Using other client-side script to reduce edits on the server
If you were interested in moving as much of the business rule logic to the client as possible, you
might use other client-side scripting languages, such as JavaScript. By exploiting ColdFusion form
tags, you moved most of the responsibility for the business rule checking from the server to the
client. This section explains how to migrate cross-field business rules to the client using
JavaScript.
Web browsers can execute scripts based on events triggered on the current page. One of the most
popular scripting languages is JavaScript. ColdFusion Form tags include an
onValidate attribute
that lets you specify your own JavaScript function for custom validation.
The JavaScript form object, input object, and input object value are passed to the specified
JavaScript function. The function returns True if validation succeeds and False otherwise. The
onValidate and validate attributes are mutually exclusive.
Recall the Compass Travel New Trip business rule 6:
Business rule 6: The trip departure and return dates must be specified for each trip. All trip dates
must be valid future dates. Departure date must precede return date.
One reason this rule is a good candidate for a JavaScript function is that the test for a future date
cannot be done using the ColdFusion form tags attributes such as
validate and range. The
following JavaScript function (
isitFutureDate) tests whether a date is a valid future date:
function isitFutureDate(oForm, oTag, dateString) {
/*
function isitFutureDate
parameters: oForm, oTag, dateString
returns: boolean
oForm is the CFForm object. All onvalidate calls pass this argument.
This function ignores it.
oTag is the CFForm current tag object. All onvalidate calls pass this
argument. This function ignores it.
dateString is the value of the current tag object. It should be a date passed
as a string in the following
format: MM/DD/YYYY. This means that months and days require leading zeros!!
Returns True if the date passed is greater than today's date
Returns False if the date passed is NOT greater than today's
date.
*/
// Check to make sure the date is zero filled with 4 digit year and
//therefore 10 characters long.
if (dateString.length != 10)
return false;
var now = new Date();
var today = new Date(now.getYear(),now.getMonth(),now.getDate());
var testdate = new Date(dateString.substring(6,10),
dateString.substring(0,2)-1,
dateString.substring(3,5));
if (testdate > now)
return true;
else
return false;
}