« What's Behind That TinyURL? | Main | Writing an Email Autoresponder Script with PHP »

Contextual Form Field Labels with ColdFusion

I think that form field labels should be used to give users feedback about the status of the field: whether it's required, or whether they've filled it out correctly. If a user didn't fill out a field correctly and you need to send them back to the form again, you can use a ColdFusion custom tag to highlight form labels to instantly show users which fields need their attention. Personally, I really like it when web sites go the extra mile to do this for me, and conversely I get annoyed when a site makes me search around in their form because they haven't clearly indicated which field or fields needs correction.

So here's the code I use to give these "contextual" form field labels. First the form code:

<cf_inputlabel for="password1">Password:*</cf_inputlabel> <input type="password" name="password1" value="">

And here's the code for the inputLabel.cfm custom tag:

<cfsetting enablecfoutputonly="yes">

<!--- Initialize paramters --->
<cfparam name="ATTRIBUTES.for" default="none">
<cfparam name="ATTRIBUTES.errorMessage" default="">
<cfparam name="ATTRIBUTES.errorClass" default="">
<cfparam name="ATTRIBUTES.errorStyle" default="color: ##990000;">
<cfparam name="CALLER.stErrors" default="#StructNew()#">

<cfif ThisTag.ExecutionMode EQ "start"><!--- If the tag is in start mode --->
<cfoutput><label<cfif Len(Trim(ATTRIBUTES.for))> for="#ATTRIBUTES.for#"</cfif><icfif StructKeyExists(CALLER.stErrors, ATTRIBUTES.for)> style="#ATTRIBUTES.errorStyle#"</cfif>#ThisTag.generatedContent#</cfoutput>
<cfelse><!--- Else the tag is in end mode --->
<cfoutput></label><i/cfoutput>
</cfif>

<cfsetting enablecfoutputonly="no">

The first time the form is displayed, the field label shows up in whatever text color you have set as the default in your CSS. But after the user submits the page and there's an error with the field-- say, their password doesn't meet your complexity requirements-- then you run code like this:

<!--- If the form was submitted --->
<cfif IsDefined("FORM.register")>
<cfset stErrors = StructNew()>
<cfif Len(FORM.password1) lt 8 or not Refind('[0-9]', FORM.password1)>
<cfsavecontent variable="stErrors.password">The password you entered is invalid.</cfsavecontent>
</cfif>
</cfif>

Then the form is shown to the user again. Since the stErrors structure contains a key named "password", then the field label will be show with whatever error styling you pass to the tag (or red by default).

Post a comment