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