Improving the error message

an article added by: Jill Babcoff at 04072008


In: Root » Computers and technology » Programming » Improving the error message

French Spanish Portuguese Italian German Japanese Chinese Korean Russian Arabic

Recall that the validation error message read, A value must be entered for the USERNAME field. That happened automatically, and ColdFusion simply used the name of the form field that was being validated. It did uppercase the entire field name for us (we just used username), and the on-screen prompt does simply ask for USERNAME. Although it’s not really about validation per se, consider that some users may be confused by a prompt on-screen requesting their Username. Most computer people recognize that as a prompt for the user’s authentication identifier, often called a username or userid. A user may possibly enter his real name (bob or bob smith) rather than what you were expecting (perhaps bsmith?). This raises the issues of usability and human factors that are beyond the scope of this discussion, but at a minimum, consider prompting users for their Login or LoginID. Consider, too, that if you’re developing an application from scratch, you may have better ways to uniquely identify a user than to force him to create and remember a contrived username. Perhaps the user’s e-mail address would suffice, or an employee number if that’s commonly known by all users of a corporate application. Of course, if this is leveraging the username of an enterprise security domain, prompting for that username or userid, however, it’s known in that environment may make perfect sense. But what if the form field name was something more obscure, such as uname? Users don’t normally see form-field names (they see only the prompts you offer), and you may want to add this validation capability to an existing application where the developer wasn’t as concerned about making the form-field name more descriptive. You certainly don’t want to change the name of the form field just so that this validation message is more understandable, because then you would need to change all the variable names on the action page as well. More important, maybe you’d simply rather have a friendlier tone to the error message, such as Please provide your username.

The good news is that you can solve both these problems, simply by providing an alternative message in the value attribute of the hidden field, as in the following example:

<input type=”hidden” name=”username_required”
   value=”Please provide your username.”>

Now, as the form is validated, if the username is not provided, the user will receive our custom error message instead of ColdFusion’s default error message. There is a bug in ColdFusion MX where the custom error messages for required form fields are being ignored. This is a known issue with Macromedia and is scheduled to be fixed in their upcoming ColdFusion MX Updater 2, which should be available for download by the time this article is published. Although the string provided for the value attribute can just be any wording that you want displayed, putting additional HTML within the string is also acceptable. Because it’s simply passed through to the browser, you could, for example, use <b> or <strong> tags to add some more formatting to your error messages.

Okay, so the value attribute enables you to improve the wording of the error message, but what about the overall appearance of the screen in which it’s offered? How does this message affect the overall appearance of your colorful application, with its pastel-blue body background and suitable text colors, to suddenly appear on-screen with its black Times Roman text on a white background? And what about your site’s navigational toolbar? If a user has questions about the error that appears, how can he find your Contact Us page? Users don’t even see your standard footer with a link to the Webmaster. Suddenly, this nifty automatic tool doesn’t look as useful as it did at first glance. Indeed, many developers have simply abandoned it for this very reason. It’s a problem that can be solved, however, at least to a greater degree than leaving the page in this plain blackon- white format. You can control the entire layout of the page (color, font, and so on) by using normal HTML tags. You can even place your navigational toolbars and other features right on the page. The solution is to add to your code CFERROR type=”validation”, which enables you to designate an error handling template of your own creation to format the appearance of just these validation errors.

The last of the three problems identified in the part above regarding the use of this automatic server-side validation may be the worst of all, and for many, it’s reason enough to not even recommend the use of server-side automatic validation. The problem is that the process requires the user to “use the back button on your Web browser to return to the previous page and correct the listed problems.” Is that a good thing to recommend? Probably not. In some instances, doing so causes the information that was entered on the form to be lost! Imagine the frustration of a user spending a good bit of time filling out a registration form that’s asking for several pieces of data. S/he submits it, is told that it contains an error (maybe just one mistake), and the user hits the Back button only to find that the form is cleared! And you can do absolutely nothing about this problem. It’s generally related to browser caching issues that aren’t easily controlled. You may be thinking that this isn’t that big a deal anyway, because failing the required validation means that the user didn’t enter anything for the required field in the first place, but consider that you may be asking for several fields of data, of which only one fails the validation. The issue isn’t that serious if the prompt is just for username and password. But in a more complex form, it could indeed become a major problem. Just be sensitive to the challenge. Fortunately, alternatives exist in the client-side validation that we discuss later. For now, you do have other kinds of validations that you can perform by using this automatic server-side validation. After you understand how the process works in general, you need to learn about the other directives.

Besides the _required validation, several more provide some of the simple validations that we listed earlier in this article. As straightforward as these options may appear, you need to be aware of certain issues for most of them. Many of these issues revolve around the fact that, in addition to merely validating the data entered, the validation process also changes the data in some cases before it passes on to the action page—and in ways that may not be obvious nor expected, as the following list describes:

_integer: If the number entered by the user contains commas or dollar signs, these characters are removed for the validation and are not passed to the action page. The documentation also says that it rounds the number entered if it includes decimal values, but in fact, it simply truncates them.

_float: Removes commas and dollar signs the same way that _integer does, but also converts the number (as presented on the action page) so that it has six places after the decimal, filled with zeros.

_range: Expects the range of values to be specified in the value attribute as min=xxx max=yyy, separated by a space. It also treats numbers the same as _float does (permitting decimal values and converting the number so that it has six places right of decimal, as well as removing commas and dollar signs). _range can also specify just one boundary. (But it must place a space after the number, as in min=5 . It can’t state min=5 with no space, at least prior to Version 5, as doing so would cause a severe bug.) Finally, because the range is specified in the VALUE attribute, you can’t offer a customized message for a failed range validation.

_date: Accepts a wide range of formats, such as 12/2/01, 12/2/2001, and even 12-2-01, 12/2, December 2, Dec 2, and so on. More important, it converts the date entered to an ODBC date format: 12/13/01 becomes {d ‘2001-12-13’}. This is fine if you’re storing the value in an ODBC database (because it saves you the need to convert the date to that format), but if it’s needed for display on an action page (or stored in a non-ODBC database), you need to convert it. Be aware of the DateFormat() function, which is available for use to convert the new version back to a regular date format. If the year is left off a date, this directive assumes the current year. If only a single number is entered, however (perhaps in intending a date in the current month), it doesn’t work at all. This single number is rejected as an invalid date. _date does accepts European-format dates (day before month), if it’s the only way that the date could possibly be valid: 13/12/01, therefore, is accepted and becomes {d ‘2013-12-01’}. Even so, using the _eurodate option is preferable to using just _date if your users are entering their dates in the European format. Oddly, if the value entered is either not a valid date (13/13/13) or not a date at all (x), the default message for both is simply: The value entered for the formfield field (‘value’) is not correctly formatted. Doesn’t really convey that it needs to be a date, much less a valid one. This suggests that you really should provide a custom message.

_eurodate: Shares all the facets of _date. The only difference is that the default format expected is the European order of day, followed by month (and then, optionally, year).

_time: As does _date, this directive not only validates the time but also converts it to an ODBC time format: 1:12 becomes {t ‘01:12:00’}. As with _date, this conversion is fine if you’re storing the data in an ODBC database (as it saves you the need to convert it to that format), but if it’s needed for display on an action page (or is stored in a non-ODBC database), you need to convert it back by using the available TimeFormat() function. _time accepts a/am/a.m. and p/pm/p.m. for a period designation. If the designation is left off, it assumes am. You also can enter just an hour and a period designator, such as 10am, which assumes that hour (10:00:00). If only a single number is entered without a period designator, however, perhaps because the user is intending to mean a time in the morning, that value is rejected as an invalid time. Strangely, if a date is entered, it accepts it, but coverts it to the value {t ‘00:00:00’}, meaning midnight. (Such a result may be logical but is not likely expected by most developers.) A few other general issues apply to one or more of these server-side validations, as the following list describes:

As demonstrated in the examples earlier in the article, where we were validating both the username and password fields, you can, of course, validate more than one field at a time in a form. You simply add a hidden-field tag for each field that you want to validate. The error message displayed reflects all the validation errors that occur.

You can also specify more than one validation per field. To indicate that an Age field is both required and must be an integer, for example, you simply create two hidden-field tags named age_required and age_integer, respectively.

Adding a validation rule to a field does not make it a required field. You need to add a separate _required hidden field if you want to ensure user entry.

You may be worried about the effect on server-side processing time if it’s always performing this validation. Any time lost is negligible, really, compared to more important performance-draining facets. You do face one unfortunate issue, however, that you must always remain aware of: CF action pages always look at a form to determine whether it contains fields ending with the suffixes. Furthermore, it then removes those fields from the list of form fields used in the database update tags CFINSERT and CFUPDATE. This could cause a problem if you have such a field in your database as Joined_Date (meaning the date that a user joined your service). CF would see any form field containing that name (Joined_Date) as a validation for a “joined” field. Worse, because it would then remove that Joined_Date field before processing CFINSERT or CFUPDATE, you may find that the column is never inserted/updated. Again, just be aware of the issue. It’s often a source of very difficult-to-resolve bugs. So that’s a quick rundown of the automatic server-side validation. It’s a feature that has its plusses and minuses. But an overriding concern should be that, because server-side validation forces the user to backup to correct any errors, it really should not be used if the form asks the user for more than a couple input fields. (And you see later that hand-coded serverside validation is used for other purposes entirely.) Instead, if you need to validate several form fields, you can provide a much better user experience by using client-side validation, and the automatic features in CF make this quite easy to do, even if you don’t know JavaScript.

legal disclaimer

Our website is not responsible for the information contained by this article. Web-articles is a free articles resource.
Suggestion: If you need fresh, daily updated content for your website, feel free to use our service. Click here for more information.

related articles

1. ColdFusion Can Be Extended In Many Ways
In addition to being one of the easiest Web-programming languages, ColdFusion is also one of the most easily extensible languages, because it can interface with many different technologies, as shown in the following list: Java objects, which are standalone packages of code written in the Java language Custom tags written in C++ or Java, which are pieces of code to be used only with ColdFusion, but which are written in either C++ or Java Java Server Page (JSP) tag libraries, which are originally built for use w...

2. First ColdFusion Application
You learn by doing, and then we go back and explain how ColdFusion worked its magic. Before you get started, though, you must learn a few terms, set up the database, and create the Web directory that you’re going to use. These are some terms that you should know: A template is a file with a .cfm extension. ColdFusion executes these templates and produces HTML that is returned to the user’s browser. A page is what appears in your browser. It is rendered from the HTML that ColdFusion Server sends back ...

3. Building the company add action template
In this article, you create the template that puts your form data into the database. Create a file named CompanyAddAction.cfm inside the Ch02 directory, type the code into the file’s editing window, and save the file. <cfquery name=”InsertCompany” datasource=”#Request.MainDSN#”> INSERT INTO Company( CompanyName, Address, City, State, ZipCode, Comments ) VALUES ( ‘#Trim(Form.CompanyName)#’, ‘#Trim(Form.Address)#’, ...

4. Modifying a Company in the Database
The data that CFQUERY requests from the database comes back in a result set, and the Name attribute tells ColdFusion what that result set is to be named. The SQL statement consists of three clauses: SELECT, FROM, and ORDER BY. SELECT tells the database which columns to retrieve from the database; FROM tells the database which table to retrieve those columns from; and ORDER BY tells the database how to sort the results. The result set returned from CFQUERY contains multiple rows of data, and each row has multiple columns. It would ...

5. Building the company edit action template
The code in CompanyEditAction.cfm is like the code in CompanyAddAction.cfm, but the edit action updates rather than inserts. Create a file named CompanyEditAction.cfm inside the Ch02 directory, type the code into the file’s editing window, and save the file. <cfquery name=”UpdateCompany” datasource=”#Request.MainDSN#”> UPDATE Company SET CompanyName = ‘#Trim(Form.CompanyName)#’, Address = ‘#Trim(Form.Address)#’, City = ‘#Trim(Form.City)...

6. Adding a New Employee to the Database
The CFQUERY in CompanyDeleteAction.cfm uses a DELETE statement with two SQL clauses: DELETE and WHERE. DELETE tells the database the table from which to delete a record, and WHERE tells the database which record to delete. You can watch the company delete process in action. Point your Web browser to http://<yourserver>/CFMXBible/Ch02/CompanyGetDeleteForm.cfm and enter a CompanyID. (To get a valid ID, go to the company list and pick a number from the ID column.) Click Submit to see the chosen company’s informatio...

7. Modifying an Employee in the Database
The DateFormat() function around the DateOfBirth column in the codereturns the employee’s birth date reformatted according to a display mask. DateOfBirth normally comes back from the database in the following format: 2002-01-01 00:00:00.0 That format is not very user-friendly. Calling DateFormat() with a mask of “mm/dd/yyyy” returns the date as follows: 01/01/2002 This version is, of course, more natural and easy to read. The same is true for the employee edit process...

8. Removing an Employee From the Database
The user must have the capability to remove employees from the database. The employee delete process is a simple combination of techniques that you have already learned, such as retrieving a record from the database, displaying that record in a template, and so on. The first page in this process is nearly identical to the employee get edit form. Create a file named EmployeeGetDeleteForm.cfm inside the Ch02 directory, type the code into the file’s editing window, and save the file. <html> <head> <ti...

9. Making direct links to the forms
Say that you want to modify or delete a company. Right now, you need to remember the company’s ID, go back to the launch pad, click Company Edit, and enter the company ID, all just to get to the edit form. Wouldn’t you rather click a company in the list and go directly to the edit form? ... <table> <tr> <td><b>ID</b></td> <td><b>Name</b></td> <td><b>Address</b></td> <td><b>City</b></t...