Using cftextarea maxlength to limit number of characters entered into cftextarea field

ColdFusion 9
MS SQL Server 2005

Hi. I've been reading documentation to find a clear answer, but I have not met with success. I want to limit to 255 the number of characters entered in my cftextarea field. But ColdFusion disregards the onSubmit validation and gives me a "truncated data" error. What else can I do here to get CF to set maxlength to 255? I know there are javascripts to do this but, because I am stubborn, I want to know why this is not working per the Adobe documentation. Thank you as always. Eric
<cftextarea name="Excerpt"
   			width="770"
			height="200"
            style="width:770px;height:200px;"
            wrap="virtual"
            maxlength="255"
            validate="maxlength"
            validateAt="onSubmit"
            message="Maximum length of News Excerpt is 255 characters.">
 
            <cfoutput>#form.Excerpt#</cfoutput>
   
			</cftextarea>

Open in new window

LVL 3
Eric BourlandAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Brijesh ChauhanStaff IT EngineerCommented:
Hey eric, Did a small test, it works for me !!

<cfform> 
<cftextarea name="txtarea" 
maxlength="5" 
validateat="onSubmit" 
required="yes" 
message="You Must Enter Max 5 Characters" 
validate="maxlength" 
rows="10" 
cols="35">
</cftextarea> 
<cfinput type="submit" name="subbtn"> 
</cfform>

Open in new window

0
Brijesh ChauhanStaff IT EngineerCommented:
See the attached screenshot..
Untitled.png
0
SidFishesCommented:
works for me too.

One Possiblity - Since CFfrom is basically just a JS wrapper (which btw, kind of kills your use cf instead of argument :P ), it can in some cases be broken by other JS errors. Check for errors with firebug or some other tool.
0
OWASP: Avoiding Hacker Tricks

Learn to build secure applications from the mindset of the hacker and avoid being exploited.

SidFishesCommented:
one disclaimer on the works for me too - I'm on CF8
0
Eric BourlandAuthor Commented:
>>> (which btw, kind of kills your use cf instead of argument

=) True this.

Brij and Sid, good to hear from you. I am working on this and will come back here with my results in a little while. Thank you! Eric
0
Gurpreet Singh RandhawaCEOCommented:
Hey!

Are you getting any Error message or it just skips the validation! if you are on Shared host, JUST Check the Mapping of the CFIDE Folder to your website!

or you can load your own CFIDE Folder into your ftp wwwroot and i hope that may be the issue, because i tried on my local and remote server, the code works!

:)
0
Eric BourlandAuthor Commented:
randhawa, good to hear from you. The error message I get just says that the data will be truncated if the form submits more than 255 characters.

Yes, I checked the CFIDE mapping -- CFIDE mappeing is set up correctly in IIS 7. In application.cfc (in the root directory) I have this line:

<!--- set path to cfform.js --->
<cfparam name="request.CFFORM_JS_Lib" type="string" default="/CFIDE/scripts/cfform.js" />

which should set the correct path to cfform.js.

My form begins like this:

<cfform method="post" enctype="multipart/form-data" scriptsrc="#Request.CFFORM_JS_LIB#">
0
Gurpreet Singh RandhawaCEOCommented:
Ok! But in your original post the message you have shown is different what you are telling here!

0
_agx_Commented:
Have you verified the path is accessible manually? ie If you enter the full path, can you view the file in a browser or do you get a 404 error?

http://www.yoursite.com/CFIDE/scripts/cfform.js
0
Eric BourlandAuthor Commented:
_agx_, yes indeed:

http://www.ncpie.org/CFIDE/scripts/cfform.js

Brij, I am setting up the test that you suggested: Sid, I will look at the Firebug output -- good idea.

randhawa, I apologize for being vague; the exact error that I get is:

Error Executing Database Query. 



[Macromedia][SQLServer JDBC Driver][SQLServer]String or binary data would be truncated. 



 



 The error occurred in C:/websites/www.ncpie.org/admin/editNews.cfm: line 67




65 :            NewsDate = <cfqueryparam cfsqltype="cf_sql_timeStamp"  value="#createODBCdate(Trim(form.NewsDate))#">,
66 :            Excerpt = <cfqueryparam cfsqltype="cf_sql_varchar"  value="#Trim(form.Excerpt)#">
67 :            		  WHERE ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#val(form.ID)#">
68 : 			</cfquery>
69 : 
 

Open in new window


I'm checking a few things and I'll report results here very soon. Thank you again. =)

Eric
0
_agx_Commented:
Not that you should rely on js validation alone anyway, but .. are you sure that's the field causing the error? If you remove it from the query does the error go away?
0
Gurpreet Singh RandhawaCEOCommented:
Ok, This is a Case where your cfform is not working, it is 99% mostly a issue with breaking cfform on your host!

The other way around is you can truncate the data like this!

<cfqueryparam cfsqltype="cf_sql_varchar"  value="#Trim(Left(form.Excerpt,255))#">

It will truncate the Message and will pick the first 255 characters of the excerpt and will not throw an error!, if somehow ur alerts is not working, to overcome the issue, you can use this!

else other way!

Wrap your query around the cftry catch block and then

use this

<cfqueryparam cfsqltype="cf_sql_varchar"  value="#Trim(form.Excerpt)#" maxlength="255">, that will handle the error in a nice way

0
_agx_Commented:
( For what it's worth, you can make that 3 in the "code works for me" category.   So as others have already said, the validation failure has to be a problem your form or configuration )
0
Eric BourlandAuthor Commented:
>>>the validation failure has to be a problem your form or configuration

I agree.

I'll report more findings in a little while. E
0
Eric BourlandAuthor Commented:
@brij -- your test code works on my web site: http://www.ncpie.org/brijtest.cfm

I enter more than 5 characters, press Submit, and get the error popup message.

This seems to me an indication that I have correctly mapped /CFIDE/ for web site www.ncpie.org, and that IIS 7 and CF 9 are configured properly, at least to handle this edit form. The problem will probably be found in my code. Am I correct? I join the "Brij's code works for me" group. Now to get Bourland's code going.

@Sid -- I viewed the page in Firefox 4 / Firebug 1.7, but I do not see any errors at all. I might be missing something.

@randhawa -- I was considering LeftTrim option, but I really want to figure out where my code is messed up. It seems like pretty simple code! I am going to check a few more things then I will report back here.

E
0
SidFishesCommented:
just one thing I noticed while error line in queries are pretty unreliable, your error points to line 67 which is

 WHERE ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#val(form.ID)#">

are you sure form.id being passed is a valid integer?
0
SidFishesCommented:
never mind val will catch that... but worth exploringif it is in fact a different field causing the issue
0
Eric BourlandAuthor Commented:
>>>are you sure form.id being passed is a valid integer?

Sid, I think so. I do CFDUMP var="#form#" and the ID = 1.

When I enter fewer than 255 characters and submit the form, the form works and the database column is populated correctly. I think the form.ID is a valid integer.

I am trying a couple more ideas. E
0
_agx_Commented:
When I enter fewer than 255 characters and submit the form, the form works

I thought it might be another field causing the error, but that strongly suggests "Excerpt" is the problem then.  

Does any of the validation work in this form, or just that field? Also, stupid question but there's only 1 field named "Excerpt" correct? (Though if there multiples you should see an error in FF's error console)
0
Eric BourlandAuthor Commented:
@_agx_:

Thinking about your notes.

Since http://www.ncpie.org/CFIDE/scripts/cfform.js resolves in a browser, I know that my mapping to /CFIDE/ is correct.

>>>Does any of the validation work in this form, or just that field?
Weird. I am getting only server-side validation. I do not get a friendly popup window that tells me I have too many characters, or I did not enter any characters in the input field.

So, for example, this input field populates the News Title; it is required:

<cfinput type="Text"
name="Title"
value="#Trim(form.Title)#"
message="Please enter a News Title."
required="Yes"
validateAt="onSubmit,onServer" 
size="50" maxlength="255">

Open in new window


But when I submit the form, I get only the server-side validation -- never the onSubmit validation.

So -- to focus more clearly on the problem -- onSubmit validation does not work in this application.

onSubmit works in the brijtest.cfm file on ncpie.org, so we know that /CFIDE/ is configured correctly; the problem is localized to this file and this form.

I am reviewing my code further. More in a while.

Eric
0
Eric BourlandAuthor Commented:
I took away all parts of the form, then added in the parts one by one until it broke.

When I omit the code for the Newsdate field, then the onSubmit validation works, and the form works as expected. All textareas submit properly. maxlength limit is obeyed.

So this code, below, neutralizes onSubmit validation. I am working to figure out why.
<p><strong>News Date:</strong> <span class="smallred">(please enter as MM/DD/YYYY, or select from calendar)</span></p>
<cfinput type="datefield" mask="MM/DD/YYYY" validate="usdate" name="NewsDate" value="#DateFormat(NewsDate, "mm/dd/yyyy")#" required="yes" message="Please enter news date as MM/DD/YYYY, or select date from calendar." onvalidate="onSubmit,onServer" />

Open in new window

0
Eric BourlandAuthor Commented:
Required fields:
Title -- cfinput type="Text"
NewsDate -- cfinput type="Datefield"
Excerpt -- cftextarea

When I enter a value into the NewsDate field (in form mm/dd/yyyy), the form does not display the onSubmit validation for any of the required fields.

If I do not enter a value into the NewsDate field, then onSubmit validation does work for all required fields.

Hmmm.
update query:
            <cfquery name="UpdatePage" datasource="#application.datasource#">
				  UPDATE ncpieNews
				  SET
           Title = <cfqueryparam cfsqltype="cf_sql_varchar"  value="#Trim(form.Title)#">,   
           News = <cfqueryparam cfsqltype="cf_sql_varchar"  value="#Trim(form.News)#">,
           Author = <cfqueryparam cfsqltype="cf_sql_varchar"  value="#Trim(form.Author)#">,
           NewsDate = <cfqueryparam cfsqltype="cf_sql_date"  value="#createODBCdate(Trim(form.NewsDate))#">,
           Excerpt = <cfqueryparam cfsqltype="cf_sql_varchar"  value="#Trim(form.Excerpt)#">
           		  WHERE ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#val(form.ID)#">
			</cfquery>

form field for NewsDate:
<p><strong>News Date:</strong> <span class="smallred">(please enter as MM/DD/YYYY, or select from calendar)</span></p>
<cfinput
		type="datefield"
        mask="MM/DD/YYYY"
        validate="usdate"
        name="NewsDate"
        value="#DateFormat(NewsDate, "mm/dd/yyyy")#"
        required="yes"
        message="Please enter news date as MM/DD/YYYY, or select date from calendar."
        onValidate="onSubmit,onServer" />

Open in new window

0
SidFishesCommented:
Wild guess

try removing the onServer

I wonder if cf is thinking oh we're validating on server so no need to valid client side
0
Eric BourlandAuthor Commented:
Sid, nice idea. When I remove onServer, no validation happens at all -- unless the NewsDate field is empty.

If I leave NewsDate field empty and submit the form, then onSubmit validation works very well.

I am wondering why cfinput type="datefield" is causing this problem, or if something else is going on.

I would post the full code here, but it's long. =)
0
Eric BourlandAuthor Commented:
I fixed it. I was sloppy. Correct code is:

<cfinput
            type="datefield"
        name="NewsDate"
        value="#DateFormat(NewsDate, "mm/dd/yyyy")#"
        message="Please enter news date as MM/DD/YYYY, or select date from calendar."
        required="yes"
        mask="MM/DD/YYYY"
        validate="usdate"
        validateAt="onSubmit,onServer" />

I had onValidate="OnSubmit,onServer"

Ugh. That was simple.
0
Eric BourlandAuthor Commented:
I spoke too soon (though it is good that I caught the onValidate error) -- after a lot of testing, I find the form is not quite working the way I want -- there are two required textareas (News and Excerpt) that still do not validate onSubmit.

The other two required fields -- Title and NewsDate -- do validate onSubmit.

When I test the two textareas separately, inside their own application just like the test that Brij sent me, then the textareas do validate onSubmit.

It is only when the two textareas are included in the full working edit document that onSubmit validation fails.

Though, now, I read this documentation: http://help.adobe.com/en_US/ColdFusion/9.0/Developing/WSc3ff6d0ea77859461172e0811cbec22c24-7a7b.html

¦Consider using hidden field validation with the cfinput and cftextarea tags if you specify multiple validation rules for a single field and want to provide a separate error message for each validation.

I will switch these two cftextarea input fields to hidden validation and let you all know what happens.

Eric
0
Brijesh ChauhanStaff IT EngineerCommented:
Eric, Just off the present post,

You can actually use JQUERY to restrict the number of characters to 225, the users will NOT be able to enter more than that, it's very simple

Below is code and demo is here.. http://www.ajaxray.com/Examples/charLimit.html 

Sorry for being off the topic, but I find Jquery a lot more easier in handling forms validations...

<script src="http://code.jquery.com/jquery-1.5.js"></script>
<script language="javascript">
function limitChars(textid, limit, infodiv)
{
	var text = $('#'+textid).val(); 
	var textlength = text.length;
	if(textlength > limit)
	{
		$('#' + infodiv).html('You cannot write more then '+limit+' characters!');
		$('#'+textid).val(text.substr(0,limit));
		return false;
	}
	else
	{
		$('#' + infodiv).html('You have '+ (limit - textlength) +' characters left.');
		return true;
	}
}

$(function(){
$('#comment').keyup(function(){
limitChars('comment', 20, 'charlimitinfo');
})
});
</script>

<form>
<textarea name="comment" id="comment" onkeyup="limitChars(this, 20, 'charlimitinfo')">
</textarea>
<span id="charlimitinfo" style=" float:left; color:#aa3333; font-size:15px; font-family:vardana" >Write your comment within 20 characters.</span> 
</form>

Open in new window

0
Eric BourlandAuthor Commented:
brij, that looks like a great idea. I will try that now. More soon. E
0
Gurpreet Singh RandhawaCEOCommented:
Hi Eric,

Great You sorted your Problem Out!

As brij Suggested, You can use the Whole Jquery to validate the Functionality of your form fields rather than making half form fields using cfinput and making some validate using jquery!

Use Jquery and You can Solve your issue for all, no messup,

Just use a Jquery Calender to pick up the date from the popup window!

Cheers

0
_agx_Commented:
It is only when the two textareas are included in the full working edit document that onSubmit validation fails


That's odd.  With onValidate fixed, it works fine "as is" for me.

<cfform>
	<cftextarea name="News"
   			width="770"
			height="200"
            style="width:770px;height:200px;"
            wrap="virtual"
            maxlength="10"
            validate="maxlength"
            validateAt="onSubmit,onServer"
            message="Maximum length of News is 10 characters." />
	<cftextarea name="Excerpt"
   			width="770"
			height="200"
            style="width:770px;height:200px;"
            wrap="virtual"
            maxlength="10"
            validate="maxlength"
            validateAt="onSubmit,onServer"
            message="Maximum length of News Excerpt is 10 characters." />	

	<cfset NewsDate = "10/15/2011">			
	<p><strong>News Date:</strong> <span class="smallred">(please enter as MM/DD/YYYY, or select from calendar)</span></p>
	<cfinput type="submit" name="submit">
	<cfinput type="datefield" mask="MM/DD/YYYY" validate="usdate" name="NewsDate" value="#DateFormat(NewsDate, "mm/dd/yyyy")#" required="yes" message="Please enter news date as MM/DD/YYYY, or select date from calendar." validateAt="onSubmit,onServer" />			
</cfform>			

Open in new window

0
Eric BourlandAuthor Commented:
I've worked on this problem for most of today. I am trying a few more ideas. I am also trying out the jquery idea from brij. I will get gack to this discussion after I have made some progress. It's been a frustrating day.
0
_agx_Commented:
Sorry to hear that. (It must be going around.. it's been that kind of day for me too) I think you're nearing the finish line.  At this point, go with what works for *you* :)
0
Eric BourlandAuthor Commented:
The jquery works very well when I set it up on its own test page.

_agx_'s code works very well when I set it up on its own test page.

When I put them into my editNews page, neither works.

I'm going to switch to another task for a while then come back to this much later tonight. Thank you friends.

Eric
0
_agx_Commented:
Eric - Any luck? Obviously if both work separately, but not in the main page the problem is somewhere in code we can't see.  Post the full form code. Maybe another set of eyes will be able to spot something you've missed.
0
Eric BourlandAuthor Commented:
_agx_, thank you. I have been looking at this for what seems like a very long time: most of yesterday. I commented the code pretty thoroughly so I hope my intentions are clear.

It is rather strange that onSubmit validation will not work for these two textareas, when they work very well in the code you and others have supplied.

* I am wondering if the TinyMCE script interferes with the onSubmit validation. I'm also wondering if TinyMCE interfered with the jQuery textarea character count gadget that brij suggested. TinyMCE modifies textarea output -- TinyMCE formats text before the text gets submitted to the database.

Here is the working example:

http://www.ncpie.org/test/editNews.cfm?ID=1

And I attach my code below.

As always I really appreciate your time. Hope your day is going well.

Eric
<!-----
Name:        editNews.cfm
Author:      Eric Bourland
Description: this interface allows a nontechnical user to create and edit database records that contain news items
Created:     March 2011
ColdFusion Version 9
MS SQL Server 2005
----->


 <!--- Set default value for ID in scope URL --->
<cfparam name="url.ID" default="">

<!--- Define ID in scope FORM, then set form.ID equal to the ID passed in the URL: for use later in the application --->
<cfparam name="form.ID" default="#url.ID#">

<cfparam name="form.Title" default="">
<cfparam name="form.News" default="">
<cfparam name="form.Author" default="">
<cfparam name="DateCreated" default="">
<cfparam name="form.NewsDate" default="">
<cfparam name="form.Excerpt" default="">

 <!--- set up protection against XSS  --->
<cfset form.Title = ReReplaceNoCase (form.Title, "<script.*?>.*?</script>", "", "all")>
<cfset form.News = ReReplaceNoCase (form.News, "<script.*?>.*?</script>", "", "all")>
<cfset form.Author = ReReplaceNoCase (form.Author, "<script.*?>.*?</script>", "", "all")>
<cfset form.Excerpt = ReReplaceNoCase (form.Excerpt, "<script.*?>.*?</script>", "", "all")>

<cfquery datasource="#application.datasource#" name="qry_editPage">
SELECT ID, Title, NewsDate, Author, News, Excerpt, DateCreated
FROM ncpieNews
WHERE ID = <cfqueryparam value="#val(url.ID)#" cfsqltype="cf_sql_integer">
</cfquery>

		   
<!---- begin CFTRY; catch errors ---->
<cftry>  
 
<!---- populate cftry with error message ---->
<cfset variables.error = ""> 
 
<!--- begin form.doSave --->

<cfif IsDefined("form.doSave")>

<!--- when an ID Exists, the action is UPDATE --->
   
<cfif val(form.ID)>
                
            <cfquery name="UpdateRecord" datasource="#application.datasource#">
				  UPDATE ncpieNews
				  SET
           Title = <cfqueryparam cfsqltype="cf_sql_varchar"  value="#Trim(Left(form.Title,255))#">, 
           NewsDate = <cfqueryparam cfsqltype="cf_sql_date"  value="#createODBCdate(Trim(form.NewsDate))#">,
           Author = <cfqueryparam cfsqltype="cf_sql_varchar"  value="#Trim(Left(form.Author,128))#">,
           News = <cfqueryparam cfsqltype="cf_sql_varchar"  value="#Trim(form.News)#">,
           Excerpt = <cfqueryparam cfsqltype="cf_sql_varchar"  value="#Trim(Left(form.Excerpt,512))#">
           		  WHERE ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#val(form.ID)#">
			</cfquery>


<!--- CFELSE: if ID does not exist, then create new record --->
				<cfelse> 
                
                
<!--- query to insert new user record into ncpieNews --->
			<cfquery name="InsertRecord" datasource="#application.datasource#" result="newPage">
				 INSERT INTO ncpieNews
     					(
                        Title,
			            NewsDate,
                        Author,
                        News,                        
                        Excerpt,
                        DateCreated
                        )
			     VALUES(
                    <cfqueryparam cfsqltype="cf_sql_varchar"  value="#Trim(Left(form.Title,255))#">,
                    <cfqueryparam cfsqltype="cf_sql_date"  value="#createODBCdate(Trim(form.NewsDate))#">,
                    <cfqueryparam cfsqltype="cf_sql_varchar"  value="#Trim(Left(form.Author,128))#">,
                    <cfqueryparam cfsqltype="cf_sql_varchar"  value="#Trim(form.News)#">,
                    <cfqueryparam cfsqltype="cf_sql_varchar"  value="#Trim(Left(form.Excerpt,512))#">,
                    <cfqueryparam cfsqltype="cf_sql_timestamp" value="#now()#">
                         )         
					</cfquery>
                    
                    
<!--- use the result attribute value (newPage) to set form field value --->
      <cfset form.ID = newPage.IDENTITYCOL>
              
<!--- END queries to update or insert database records ---> 

<!--- END cfif val(form.ID) -- if a topic needed to be updated or added, then it was done --->
					    </cfif>  


<!--- done? go to manageNews.cfm --->
				     <cflocation url="manageNews.cfm" addtoken="no">
             
<!--- END: Save action --->

<!--- END form.doSave --->
                    </cfif>
       
<!--- END queries to update or insert database records ---> 
        

<!--- this CFCATCH will trap errors --->
            <cfcatch type="Any">
                 <cfset variables.error = cfcatch.message>
            </cfcatch>

<!--- END CFTRY --->  
			</cftry>
       
       
<!--- fetch the data from the database only when there are no errors; let the form variables pass back from the data table into the form to display ---->
 
<cfif len(variables.error) eq 0>
    
<!--- get data from table ncpieNews and convert the data into form variables --->
			  <cfquery name="getPageDetails" datasource="#application.datasource#">
			    SELECT ID, Title, NewsDate, Author, News, Excerpt, DateCreated
                FROM ncpieNews
                WHERE ID = <cfqueryparam cfsqltype="cf_sql_integer"  value="#val(form.ID)#">
 			  </cfquery>

  			<cfloop index="aCol" list="#getPageDetails.columnList#">
			       <cfset "form.#aCol#" = getPageDetails[aCol][getPageDetails.currentRow]>
			  </cfloop>
    
</cfif>


<!--- if there an error, display error in readable form --->

<cfif len(variables.error)> 
			 <cfoutput>
			 <div style="border: 1px solid red; padding: 10px; margin:20px; width:400px;">#variables.error#</div>
			 </cfoutput>
</cfif>


<!----- if record already exists then update record; otherwise, add new record ----->
				<cfif val(url.ID)>
					  <cfset FormTitle="Update News">
					  <cfset ButtonText="Update">
				<cfelse>
						<cfset FormTitle="Create News Item">
						<cfset ButtonText="Send">

				</cfif>

       
       
       <!--- BEGIN HTML / CSS PAGE HEADER --->
<cfinclude template="cms_admin_header.cfm">

       <!--- this is popup window to contain inline help documentation --->
<script language="JavaScript" type="text/javascript">
<!-- Begin
function popUp(URL) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=400,height=500,left = 483,top = 84');");
}
// End -->
</script>



	<!--- Add or Update News Form begins here --->
	<cfform method="post" enctype="multipart/form-data" scriptsrc="#Request.CFFORM_JS_LIB#">
                
 
 <!--- Embed UserID (PK) to assign a value to it --->
 <cfoutput>
<input type="hidden" name="ID" value="#form.ID#" />
 </cfoutput>


<div class="edit_page_title">
<cfoutput query="qry_editPage">

<div class="float-left"><h2>#FormTitle#</h2></div>

</cfoutput>
</div>


<div class="clear-both"></div>
   
  <p><strong>News Title or Headline:</strong> <span class="smallred">Required. 255 characters or fewer.</span></p>
  	 <cfinput
     		type="Text"
			name="Title"
			value="#form.Title#"
            message="Enter a News Title."
            required="Yes"
            validateAt="onSubmit,onServer" 
			size="50"
			maxlength="255"
            tabindex="1" />
  
   <div class="clear-both"></div>
            
            
<p><strong>News Date:</strong> <span class="smallred">Required. Please enter as MM/DD/YYYY, or select from calendar.</span></p>
<cfinput
		type="datefield"
        name="NewsDate"
        value="#DateFormat(NewsDate, "mm/dd/yyyy")#"
        message="Enter news date as MM/DD/YYYY, or select date from calendar."
        required="yes"
        mask="MM/DD/YYYY"
        validate="usdate"
        validateAt="onSubmit,onServer"
        tabindex="2" />
        
        
  <div class="clear-both"></div>
            
     <p><strong>Author:</strong> <span class="smallred">Optional. 128 characters or fewer.</span></p>
  	 <cfinput
     		type="Text"
			name="Author"
			value="#form.Author#"
			size="50"
			maxlength="128"
            tabindex="3" />
            
       <!--- formatting for instructions and inline help --->            
   <!-- text above editing area -->
    <div class="row_admin">
    <div class="row_admin_left"> 
    Use the TinyMCE Editing Interface to enter and format News Content:
    </div>    
	<div class="row_admin_right">
<a href="javascript:popUp('http://ebwebwork.com/control/cms.cfm')" style="text-decoration:none; font-weight:bold;">TinyMCE Documentation</a>
	</div>
    </div>
   <!-- /text above editing area -->
     <!--- /formatting for instructions and inline help --->            
     <div class="clear-both"></div>

     <p><strong>News Content:</strong> <span class="smallred">Required.</span></p>
     
      <textarea name="News"  
                        width="770"  
                        height="500"  
            style="width:770px;height:500px;"  
            wrap="soft"  
            tabindex="4">

           <cfoutput>#form.News#</cfoutput>
   
	  </textarea>
      
      
             <!--- server-side form validation --->            
      <input type="hidden" name="News_required" value="You must enter News Content." /> 

       <!--- formatting for instructions and inline help --->
   <!-- text above editing area -->
    <div class="row_admin">
    <div class="row_admin_left"> 
    Use the TinyMCE Editing Interface to enter a News Excerpt; <em>enter 512 characters or fewer!</em> The News Excerpt displays on the front page under the News column.
    </div>    
	<div class="row_admin_right">
<a href="javascript:popUp('http://ebwebwork.com/control/cms.cfm')" style="text-decoration:none; font-weight:bold;">TinyMCE Documentation</a>
	</div>
    </div>
   <!-- /text above editing area -->
         <!--- /formatting for instructions and inline help --->            

  <div class="clear-both"></div>
  
    
     <p><strong>News Excerpt:</strong> <span class="smallred">Required. 512 characters or fewer.</span></p>
             <!--- 512 characters accommodates 99% of news excerpts required by this client, ncpie.org ---> 
             
             <!--- News Excerpts display on front page under What's New: http://www.ncpie.org/index_test.cfm --->           
     
     <cftextarea name="Excerpt"  
                        width="770"  
                        height="200"  
            style="width:770px;height:200px;"  
            wrap="soft"  
            maxlength="512"  
            validate="maxlength"  
            validateAt="onSubmit,onServer"  
            message="Maximum length of News Excerpt is 512 characters."
            tabindex="5">
            <cfoutput>#form.Excerpt#</cfoutput>
   
	  </cftextarea>

             <!--- server-side form validation --->            
      <input type="hidden" name="Excerpt_required" value="You must enter a News Excerpt." /> 
               

   <!--- submit form to ColdFusion for processing; this is the DoSave function, which will add or edit a record --->

<div class="edit_button">
  <cfoutput>
      <input name="doSave" type="submit" value="#ButtonText#" tabindex="6" /> 
  </cfoutput>
  </div>

</cfform>


<!--- Page footer --->
<cfinclude template="cms_admin_footer.cfm">

Open in new window

0
_agx_Commented:
I am wondering if the TinyMCE script interferes with the onSubmit validation

Yes, without any testing anything yet. That would be my suspicion too.
0
Eric BourlandAuthor Commented:
In the cold light of morning I am trying some new ideas for testing. I will take away TinyMCE from test page and see what happens.
0
Eric BourlandAuthor Commented:
I think it is TinyMCE that interferes with the onSubmit validation. I just took away TinyMCE and now the validation appears to work. I am running some more tests.

Probably no need to spend any more time with this.
0
_agx_Commented:
It is TinyMCE causing the problem.  IIRC it doesn't use the textarea the same way. So when you submit the form it works because the textarea value doesn't actually contain the new text you entered.

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
_agx_Commented:
Just double checked it w/Firebug and that's the issue.  Even if you append a big string to the textarea, it's length never changes. Because TinyMCE stores the text somewhere else.  So it always passes the CF validation because it's not checking the right thing.
0
Eric BourlandAuthor Commented:
_agx_,

This has been an interesting lesson. But I am very glad to know what is going on. As usual, I have learned a ton.

I am going to close this question. I will keep onServer validation. I wonder if there is a way I can adapt a jQuery to count the characters that TinyMCE stores before the form submits.

As always, thank you.

Eric
0
Eric BourlandAuthor Commented:
So, TinyMCE interferes with onSubmit textarea validation -- whether you are using ColdFusion's built-in validation or a jQuery validation. For now I will stay with onServer validation for my textareas.

Many thanks to brij, Sid, randhawa, and _agx_ -- who have helped me with this question over the past couple of days. As usual I have learned a great deal. I am very grateful.

Eric
0
_agx_Commented:
So, TinyMCE interferes with onSubmit textarea validation

Yes because it takes over the textarea's value, and stores it somewhere else. So when CF checks yourTextArea.value it doesn't get the real text.

I think you'd have to tap into the tinyMCE api to transfer the text to some field you could validate. But .. you'd also have to remove the html code to get the right character count. This works for the onSubmit validation.  

I didn't include server side because you'd need to customize it.  A straight "maxlength" validate="onServer" could yield the wrong results because it wouldn't know to remove html tags from the character count.

http://tinymce.moxiecode.com/wiki.php/TinyMCE_FAQ
     <cftextarea id="Excerpt" name="Excerpt"  
            width="770"  
            height="200"  
            style="width:770px;height:200px;"  
            wrap="soft"  
            tabindex="5"><!--- don't generate extra white space 
			---><cfoutput>#form.Excerpt#</cfoutput></cftextarea>

      <input type="hidden" id="Excert_required" name="Excerpt_required" value="You must enter a News Excerpt." /> 
	  <!--- "id" must have format: {textAreaID}_maxlength. "value" must be max characters --->
      <cfinput type="hidden" id="Excerpt_maxlength" name="Excerpt_MaxLength" value="512" onValidate="validateTextArea" message="Maximum length of News Excerpt is 512 characters." /> 

<script type="text/javascript">
	function validateTextArea(frm, fld, value) {
		var maxChars   		= parseInt(""+ value);
		var textAreaID 		= fld.id.split("_")[0];
		var textAreaElem 	= document.getElementById(textAreaID);
		var textAreaValue 	= "";
		
		// if the field exists ...
		if (textAreaElem) {		
			// transfer the text form tinymce to the textarea's
			tinyMCE.editors[textAreaID].save();
			// remove any html tags in value before validating
			textAreaValue = textAreaElem.value.replace(/<[^>]+>/g, '');			
		}
		// return true if the value is less than the max characters
		return textAreaValue.length < maxChars;
	}
</script>

Open in new window

0
Eric BourlandAuthor Commented:
_agx_:

>>>I think you'd have to tap into the tinyMCE api to transfer the text to some field you could validate. But .. you'd also have to remove the html code to get the right character count. This works for the onSubmit validation.

I see that you transferred the text to a hidden input field called Excerpt_required ... and this field gets counted. I see that you took steps to omit HTML from the character count.

... tested, and it's working.

That was a brilliant solution. =)

Thank you so much. You are a jukebox hero.

Eric
0
_agx_Commented:
> transferred the text to a hidden input field called Excerpt_required

No, that was there in the original code :) Though you could easily store the plain text if you wanted. Just store it after removing the hmtl

..
textAreaValue = textAreaElem.value.replace(/<[^>]+>/g, '');	
document.getElementById('idOfHiddenField').value = textAreaValue;
..

Open in new window


0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ColdFusion Language

From novice to tech pro — start learning today.