[Looking for Charlie's main web site?]

Getting MaxLength Validation to work with CFTEXTAREA Richtext="yes"...busted, but with a workaround

Note: This blog post is from 2008. Some content may be outdated--though not necessarily. Same with links and subsequent comments from myself or others. Corrections are welcome, in the comments. And I may revise the content as necessary.
Have you tried to use the maxlength validation with the new CF8 rich text cftextarea? You'll find that it simply doesn't seem to be working, or works inconsistently. I've done some digging and found why it's not working as it should, and I also offer a workaround for you if interested.

Now, some might point out that with CFFORM maxlength validation, you need to remember to set validate="maxlength", and that's true. And you provide a maxlength attribute and value, as well, but neither of those are what I'm talking about. Nor is it about the fact that you have to account for the underlying HTML that's generated. The validation simply doesn't work as it should, as I'll explain.

The root of the problem

Note that I say it doesn't work as it should--I'm not saying it never works. You can actually get it to trigger a maxlength failure, but it's just not working right.

Here's the deal: what's validated is the length of any data that prepopulates the field, not what the user enters into the field. In other words, it doesn't matter what you (or your user) types into the field. That will not be what's checked, but rather what was there initially. Not too useful (and confusing, for sure).

Let me be more explicit: if there's no text prepulating the field (what's between the CFTEXTAREA) or it's less than the maxlength, then the form submission will always pass without error even if you add lots of text to the field. That's certainly not right.

Conversely, if the field is prepopulated with text that exceeds the maxlength, then the form submission will always fail for the length validation, even if you remove enough text that it should pass. Again, all this could be very confusing if you don't understand what's going wrong.

As an aside, not that it matters to this problem, note that you can also prepopulate a CFTEXTAREA with a Value attribute (not something you can usually do with a normal TEXTAREA.)

A simple sample to test with

Here are 2 examples of what I'm describing. You can drop each into a page (it's a self-posting form, so it doesn't matter what you call the file):

<cfform>
Description (up to 10 characters):
<cftextarea name="description" validate="maxlength" maxlength="10" message="Description must be 10 chars or less" richtext="yes" toolbar="Basic"></cftextarea>
<input type="Submit">
</cfform>

If you run this, you'll notice that it will always pass, regardless of what you enter. Why? Because it's prepopulated with nothing, and that passes the validation, regardless of what you type.

On the other hand, the following will never pass validation, regardless of what you enter, because it's prepopulated with something longer than the maxlength:

<cfform>
Description (up to 10 characters):
<cftextarea name="description" validate="maxlength" maxlength="10" message="Description must be 10 chars or less" richtext="yes" toolbar="Basic">1234567890123</cftextarea>
<input type="Submit">
</cfform>

Obviously, none of this is what you would expect. If you've had people complaining about problems, it's no wonder that you'd be really confused.

(And of course, 10 is too low a number for general use, and unless you're doing an update form you wouldn't likely prepopulate your field as I have, but these make it easy to demo the issue.)

Maxlength validation works fine for CFTEXTAREA, as long as it's not rich text

Now, all that said, things will work just fine if you take out the richtext and toolbar attributes. Go ahead and try it. So clearly it's the richtext feature that's busted with regards to maxlength validation.

Why it's not working

I did some digging into the cfform.js file, which is where the code to do validation lives (in /CFIDE/scripts/) and I found the problem. What's passed to that validation code is not what's typed into the rich textarea (which is itself an iframe buried pretty deep in some code that the FCKEditor builds), but rather what's passed is just the HTML form field value, which in this case will be what was entered into the field when it was initialized (when the page is first loaded).

The ultimate solution is that the CF validation process needs to be changed to instead get the length of whatever was entered into the fckeditor control.

From further digging into that, with regard to some FCKEditor info I found, one might conclude it would be impossible. Many have complained about wanting maxlength validation with the control, and folks working on the tool have said it's a limitation the control.

But here's good news: I did still more digging and learned that the CF javascript API for the new ajax controls does indeed provide access to this information! Woo hoo! You can access it via the ColdFusion.getElementValue('thefieldname') method. With that, one can then test its length.

For now, it's just something you need to do manually. I'll offer some code below that presents how to do this.

Don't forget to account for the generated HTML

Before I show the code, take note about your use of any maxlength test in the richtext textarea (whether it's done by CF itself in the future or by using this manual test): you (and your users, and any messages you give them) need to take into account that the rich textarea will have a length that's longer than just what the user sees/types.

Even with just an "x" entered in a richtext textarea, the underlying content created by the control (and as submitted to the form processing) will be surrounded by paragraph tags:

<p>x</p>

So that x would then have a length of 8 chars! Just be careful that if you need to tell them they can enter no more than 100 characters, because you're entering the text into a database column of that size, then you need to make it clear that they won't be able to really type 100 characters. And the more formatting they do, the less space they'll have.

In my code below, I offer an option for the validation error message to show them the text as entered, with the html coding.

An example of some code to check the real value entered

So the answer is in using the ColdFusion.getElementValue method, passing it the name of the textarea field to be validated. Using that, and its length property, we can do the needed test. As a quick example, here's a demonstration where the cfform onsubmit method is called to display the real text entered in the field, and its length. Note that I gave the cftextarea a name of "description", and that's what I name in the getElementValue (note that all Javascript is case-sensitive, from method names, to variable names, to names of fields accessed in code):

<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">
<!--
function testlen(){
   var body = ColdFusion.getElementValue('description');
   alert('text=' + body + '\nlength=' + body.length);
}
//-->
</SCRIPT>

<cfform onsubmit="testlen()">
Description (up to 10 characters):
<cftextarea name="description" richtext="yes" toolbar="Basic"></cftextarea>
<input type="Submit">
</cfform>

With this code, whatever value you enter will be displayed, along with its length.

Now, one may point out that an alternative to using OnSubmit on the CFFORM would be to use OnValidate on the CFTEXTAREA. Well, yes and no. It would normally be a good choice, but we will see later that we will want to create a more flexible form of this code, where we will pass in the name of the field, a test length, and optionally a message to display. The OnValidate only let's you name a method to call, without naming arguments. It's designed to automatically pass in the form field value, just like the built-in validation process, but just as that doesn't work with the rich textarea, so too does it not work for this challenge.

A proposed solution to the textarea richtext validation

So with all that as preface, here then is some code I've put together that may help those wanting to do Rich CFTextArea validation. I've designed it so that you can name the field to validate, the length to test, and optionally an error message to display if it fails the validation, along with an option of whether to show the HTML-formatted generated content in the message.

<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">
<!--
function testlen(field,maxlen,msg,showval){
   /*
   Validates maxlength for a CFFORM CFTEXTAREA richtext field.
   Created by Charlie Arehart, carehart.org, 8/1/2008
   - field (required): name of rich textarea field on form to validate (case sensitive!)
   - maxlen (required): the maximum length to be permitted for the length of the textarea body (including generated html)
   - msg (optional): a message to be shown to the user, or empty string ('') to show a default message defined as "defaultmsg" below
   - showval (option): if 'yes', will show the actual generated body as part of the message
   */

   var body = ColdFusion.getElementValue(field);
   var defaultmsg = 'The ' + field + ' field must be less than ' + maxlen + ' characters.'
   // test textarea body length    if (body.length > maxlen) {
      // if no message is passed in, create a default one (the onsubmit in cfform seems to require all args be passed, so 3rd arg can't be left out, but an be set to '')       if (msg.length < 1) msg=defaultmsg;
      // show the current value, if requested       if (showval == 'yes') msg=(msg + '\nCurrent value (with HTML) is:\n' + body)
      alert(msg)
      return (false);
   }
}
//--> </SCRIPT>

<!--- note that for the cfform onsubmit, it appears you must specify all args of a called function --->
<cfform onsubmit="return testlen('description',10,'','yes')" >
Description (up to 10 characters, including HTML):
<cftextarea name="description" richtext="yes" toolbar="Basic">12345</cftextarea>
<input type="Submit">
</cfform>

<cfif cgi.request_method is "post">
   <cfdump var="#form#">
</cfif>

The key is in the call in the onsubmit to the testlen function. The comments explain that it takes the 4 arguments I mentioned. In this case, it's calling testlen('description',10,'','yes'), which is testing the "description" field, for a maxlength of 10, and I'm letting the function create the default error message, while I do want it to show the user the formatted value if they get the validation error. If you want to provide your own message, just provide that in the 3rd argument.

Now, you might think that if you want to skip the 3rd argument but privide the 4th, you could just let it be left unspecified, as in testlen('description',10,,'yes'). But for some reason the OnSubmit attribute of CFFORM doesn't like that. So just specify it as '' if you want to set the 4th arg to 'yes'.

Naturally, if you're happy with the default message and you don't want to show the formatted result to the user, you can then leave off both the last 2 arguments, as in testlen('description',10).

Note as well that you want to call the function (in the OnSubmit attribute) using the form "return testlen(...)", as I have. If you don't, then the form would be submitted anyway even if it fails the validation. By using the return, you cause the result of the function to drive whether the submission takes place, and it returns false if the length test fails.

I could make the function still more robust, testing incoming arguments and such, but it will work for most needs as long as you're careful. Again, remember that when you pass in the name the field, it must be the exact same case and spelling of the CFTEXTAREA name.

That's it. I hope it's helpful. Please let me know what you think in comments, whether it helps or if you see a problem, etc.

Let's hope this is addressed in the CF engine

It would sure be nice to see Adobe get this fixed in the engine. I hope this may help. I'll file a bug report pointing back to this for the details. I've already filed it in the LiveDocs as well.

I will say that if this problem remains into the next release, then the MaxLength attribute and validate="maxlength" option should be removed both flagged as unavailable for CFTEXTAREA when richtext="yes".

For more content like this from Charlie Arehart: Need more help with problems?
  • If you may prefer direct help, rather than digging around here/elsewhere or via comments, he can help via his online consulting services
  • See that page for more on how he can help a) over the web, safely and securely, b) usually very quickly, c) teaching you along the way, and d) with satisfaction guaranteed
Comments
Charlie,

Thanks for such a thorough follow up to my question!

This really underscores how tricky MaxLength validation is with any rich text editors.

The ideal solution it seems to me would be to have a counter that lets the user know how many characters they have remaining. This would be a really nice feature to have built into the cftextarea tag both for rich text and non-rich text.

Ray
# Posted By Ray Buechler | 8/4/08 9:59 AM
Glad to have helped, Ray, and yes, a "countdown counter" would be a nice addition.

The good news is that there are many scripts out there to add that, that one could add manually--certainly for the plain CFTEXTAREA (or any TEXTAREA), but possibly also for the richtext one. I showed interacting with the data onsubmit, but I don't doubt it could be interacted with during input as well. (Maybe not, but I'll leave others to explore that. Hope they'd report here if they read this and do.)

But I agree as well that it would be nice for all this to be built in. It's just the kind of thing you ought to report on the CF wish form: http://adobe.com/go/... The CF team reads those, and have said that they often don't work on things (even if mentioned in lists and blogs) if it's not entered there. Please do go file this great feature request there. :-)
Charlie,

The Spry textarea widget is fairly robust in terms of counter options. I have used it quite a lot. (http://labs.adobe.co...).

Feature request has been submitted via the wish form. :)
# Posted By Ray Buechler | 8/4/08 12:06 PM
This is great stuff Charlie.

Any suggestions on how to execute a javascript function when the CFTEXTAREA loses focus... any solutions for onBlur?
# Posted By Alex S | 1/7/09 11:21 PM
@Alex, glad it may have helped. As for your observation, I think you've identified a bug. I can't tell if it's in CF or in the FCKEditor, but yes, if you specify an onblur event, it does not fire. The curious thing is that it's passed through to the browser, but it just never fires. I added a text field to a test form with a richtext textarea (that had an oblur="alert('left textarea')", and when I click on the new test field, it does not show the alert. But if I change it from a cftextarea to a plain textarea, it does show the alert.

This is one worth reporting on the Adobe wish/bug form (see http://carehart.org/...).
What's even more curious is that if you set toolbarOnFocus="true", the toolbar will show and hide as the cftextarea field gets and loses focus.

We should be able to hook into this event and run a custom JS script.
# Posted By Alex S | 1/8/09 9:17 AM
Was running CF 7.0.2 with Access 2003 in the background. Forms were working fine until last Monday. Server OS is Win Server 2003. Problem: users cannot enter a carriage return in my textarea(Variable name: GOOD) or more than 250 characters. The field in the db that houses this data is a memo field, so there shouldn't be a problems there. A little more background. I've since upgraded to CF9 and Access 2010. Same problem.
# Posted By Roland | 1/15/11 2:48 PM
@Roland, sorry, but I don't recognize your problem and can't suggest a solution. Best to raise this on one of the CF forums at Adobe (http://forums.adobe....).
Charlie,
I have a question that there is a letter list in rich text area in coldfusion 9? (A,B,C)

I know that there is a numbered list and bulleted list in rich text area in coldfusion 8.

Thank you so much for your help!

Ha
# Posted By ha | 5/27/11 2:01 PM
@Ha, I'm afraid I just don't know.
How would you use this function for multiple cftextareas on the same cfform?
# Posted By Dwayne | 1/18/13 6:59 AM
@Dwayne, you would simply call the testlen function for each field, passing in its name. If you may mean, how would you do it in the onsubmit attribute of CFFORM, well, now this is then really a simple question of the many ways to call a function in Javascript.

Note that I was doing it as a shortcut in the return keyword, but you could also do it in an onblur for the specific CFTEXTAREA in question, so that when they leave that field, it's checked. You could also do it for all fields at once by creating a new function which does all the lengthchecks for each field, and then call that function from the onsubmit.

I'd propose that you'd be best off studying more about calling javascript functions on a web page, as it's a generic question for which you'd find ample resources on the web.

Hope that gets you started and points you in the right direction.
Copyright ©2024 Charlie Arehart
Carehart Logo
BlogCFC was created by Raymond Camden. This blog is running version 5.005.
(Want to validate the html in this page?)

Managed Hosting Services provided by
Managed Dedicated Hosting