Generic HTML Form error handler

The guy I share an office with is a flex developer and often has problems with simple ColdFusion tasks like form error handling because he doesn’t do them enough. Perhaps others deal with the same situation.

Here’s a generic form error handler.

First, add a little snippet to the form display. I always change the form field label to red if the user did not enter data.

<span style="font-weight:bold;color:<cfif ListFindNoCase(form.errorfields, 'email')>red<cfelse>black</cfif>;">Email Address:</span>
<input type="text" name="email" value="<cfoutput>#form.email#</cfoutput>">

You notice the form.errorfields right? That gets generated in the event/error handler code.

// check for errors in form fields
for (i = 1; i LTE ListLen(form.fieldnames); i = i + 1) {
	if (NOT len(trim(form[ListGetAT(form.fieldnames, i)]))) {
		form.errorFields = listAppend(form.errorFields, ListGetAt(form.fieldNames, i));
	}
}

This simply checks to make sure all fields have data. It does not check the validity of that data so you will need to add that yourself. For an email field, add something like:

if (IsValid(”email”, form[ListGetAt(form.fieldnames, i)])

(This is CF7 specific)

One thing to note is that Radio buttons will not show up in the form.fieldnames if there is not a default value. To add them manually do:

form.fieldnames = ListAppend(form.fieldnames, “radioButton”);

If a field is not required, remove it from the list by doing this:

form.fieldnames = listDeleteAt(form.fieldnames, ListFindNoCase(form.fieldnames, “submitButton”));

Once again, this is very generic and can be extended to be much more robust. But, for a simple form, this works great.

Leave a Reply