HOME | FERGUSON Digital Blog

Auto Trim Form Fields

ColdFusion Add comments

When a user submits a form to a website, they don't always send the be best formed responses in the form fields. Take leading and trailing spaces for example. For whatever reason, some folks seem to rest on the long key before or after their thought is translated to the hands and they type the response.

When entering this information into a database, the best action to take is to just use the Trim() function around the form variable. This is particularly helpful if your code was expecting a number and not spaces (converting their response into a CHAR).

<cfqueryparam value="#Trim(FORM.SomeValue)#" cfsqltype="CF_SQL_VARCHAR">

Not every form submission goes into a database, but trimming the fields of leading or trailing spaces will still be necessary. Here is CFSCRIPT that uses the StructKeyExists() function to determine if a page has FORM submissions. Using DO and WHILE, the loop progresses through the FORM.FieldNames structure and replaces each entry with a trimmed value.

While we're at it, we are going to ReReplaceNoCase() any HTML tags that may have ended up in the form submission. Just place it into the onRequestStart of an Application.cfc page and let it take care of the rest.

<cffunction name="onRequestStart">
   <cfargument name="RequestName" required="yes" />
   <cfscript>
      //Automatic TRIM of all FORM field submissions
      if (StructKeyExists(FORM, "FieldNames") AND ListLen(FORM.FieldNames) GT 0) {
         FormIndex=0;
         do {FormIndex++;
            FORM[ListGetAt(FORM.FieldNames, FormIndex)]=Trim(FORM[ListGetAt(FORM.FieldNames, FormIndex)]);
            FORM[ListGetAt(FORM.FieldNames, FormIndex)]=REReplaceNoCase(FORM[ListGetAt(FORM.FieldNames, FormIndex)], "<[^>]*>", "", "ALL");}
         while (FormIndex LT ListLen(FORM.FieldNames));}
   </cfscript>
</cffunction>

The trim can be tested with a form page submission to itself with a CFDUMP of the form field and the Len() function.

<cfdump var="#Len(FORM.TestField)#">

<form action="<cfoutput>#CGI.SCRIPT_NAME#</cfoutput>" method="post">
   <input name="TestField" type="text" />
   <input name="submit" type="submit" />
</form>

Try this with and without the auto trim and see that the length of the TestField value will change with leading/trailing spaces.

If you find this post useful please leave a comment and let me know how you used the information.

0 responses to “Auto Trim Form Fields”

Leave a Reply




© Copyright 1997-2024, All Rights Reserved Coldfusion and MS SQL2008
Powered by Mango Blog.   Design by FERGUSON Digital
o:Event name="beforeHtmlBodyEnd" />