Any user input that is reflected back to users in a web application is a potential vector for cross-site scripting and similar code injection attacks by marauding nasties. One way to thwart these reprobates is to encode special characters in the user input before saving or displaying it. And in ColdFusion, xmlFormat is available to help with that.
It’s also good practice to enforce maxlengths on user input. But if we allow special characters and then sanitize them with xmlFormat, the maxlength on the text field will no longer match the size of the string that we then need to store.
That’s because those special characters will be escaped. An apostrophe uses one character when the user inputs it but 6 when it has been escaped:
How do we calculate the column size to store our expanding string?
Easy. The longest escapes produced by xmlFormat are ' and the ASCII characters 128 to 255, which also take six characters (eg É). So the column size is simply (maxlength * 6).
If we are enforcing a maxlength of 50 characters on the text field, then the longest string we need to store in the database will be 300 characters.
NOTE: Calculating the column size doesn’t mean you don’t have catch and handle truncated data errors! Just because you enforce a maxlength via HTML doesn’t stop evildoers posting parameters of arbitrary length to your application. The first thing an attacker will do is reconnaissance on your application, which means fuzzing those parameters until it breaks. With luck, the platform or a web application firewall will be there to keep errors from leaking juicy info about the app, but let’s not rely on it. It pays to be a little paranoid.
Besides, handling errors gracefully is a hallmark of elegant code. We all prefer elegant code to ugly hacks, right?