How Get length of Textarea (not CFtextarea) but CF8 backend

Ian White
Ian White used Ask the Experts™
on
I have a non cold fusion form that has a text area - it will not become a coldfusion form.

In the CF8 action page I want to test how much text - how long is the text area.
If it is too short - the user will receive an error message to add more description - eg at least 5 lines.

Please how do I test eg form.textarea passed from no cf form.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Once a page is generated, there is no coldfusion on that page at all, so it doesn't matter if the page was created by coldfusion, asp, simple html, etc.

However, if your action page is coldfusion, then you can use coldfusion to test it..

<cfif len(form.textarea) lt 1000>  
    ... you must enter at least 1,000 characters... keep talking!

</cfif>
btw if you want to count the characters inside the textarea, you can always do the simple in coldfusion

<cfset wordswritten = len(form.textarea)>
<cfset remainingWords = 1000 - #wordsWritten#>
<cfif wordsWritten NEQ 1000>
Please Provide Max of 1000 characters at least, you are missing atleast #remainingWords# characters yet
</cfif>

Also another will be using javascript:

<script>
function limitText(limitField, limitNum) {
    if (limitField.value.length > limitNum) {
        limitField.value = limitField.value.substring(0, limitNum);
    }
}
</script>

<form name="myform">
textarea limit 20 chars :<br>
<textarea rows="5" cols="30" onKeyDown="limitText(this,20);"
onKeyUp="limitText(this,20);">
</textarea><br>
</form>

one way @gd has already told u
Top Expert 2013
Commented:
Simply test the length before submitting. In the action for the form use:
action="javascript:testLen();"

then the script in the head is:
<script type="text/javascript">
function testLen()
{
    if (document.getElementById('idoftextarea').innerHTML.length() < 1000)
    {
         alert('your error message');
    }
    else
    {
        document.forms[0].action="yourpage.html';
        document.forms[0].submit();
    }
}
</script>

Open in new window



Cd&
11/26 Forrester Webinar: Savings for Enterprise

How can your organization benefit from savings just by replacing your legacy backup solutions with Acronis' #CyberProtection? Join Forrester's Joe Branca and Ryan Davis from Acronis live as they explain how you can too.

Client side messaging and validation is a great idea as suggested by myselfrandhawa and enhanced by Cobol, but do keep the server side validation as well.   You can't validate a page with just javascript.
Top Expert 2013

Commented:
You can't validate a page with just javascript.

I absolutely agree.  The validation on the client side should just be considered a coarse filter to reduce the demands on server resources.  Full validation, sanitizing, and other security filtering is essential on the server before any user submitted data is used for processing or db updates.

Cd&
Ian WhiteOwner and Founder

Author

Commented:
Thanks - I have the server side working fine, but would also like to trap on the client end.
The page was designed using jquery validation so I though I would stick to that to stay consistent - but does not appear to work. I put the code in to desc.cfc  - remote/ajax call

In JS
Desc: {
      required: true,
      remote: 'ajax/desc.cfc?method=chkDesc'
                        },
.....

messages: {

            Desc: {
                              required: 'Please enter your description',      
                              remote: 'Please enter at least 4 lines of description'
                        },

.....

<!--- Make sure 3 lines of description --->

<cfcomponent>
      <cffunction name="chkDesc" access="remote" returnformat="json" output="false">
        <cfargument name="desc" required="true">

<cfparam name="wordswritten" default="0" type="numeric">
<cfparam name="remainingWords" default="0" type="numeric">

<cfset wordswritten = len(arguements.desc)>
<cfset remainingWords = 180 - #wordsWritten#>
<cfif wordsWritten LT 180>
              <cfset returnDesc  = false>
        <cfelse>
              <cfset returnDesc  = true>
</cfif>        
    <cfreturn returnDesc>
    </cffunction>
</cfcomponent>
have you included the required jquery  validation files for the same, what error you are getting in the firebug, can you please provide us
Ian WhiteOwner and Founder

Author

Commented:
Yes the jquery files are there as it does a lot of validation ok already

there is no error in firebug - it is not getting invoked from notes

It works ok for username and email on the same page -- see below. For some reason not getting invoked from the notes field?
 
            EmailAddress: {
                             required: true,
                  email: true,
                  remote: 'ajax/email.cfc?method=chkEmail'

      },
            UserName: {
                  required: true,
                  regex: '^[A-Za-z0-9_]{6,20}$',
                  remote: 'ajax/username.cfc?method=chkUsername'
                }
AveAGo,

It doesn't make sense for your client side validation to use ajax and call the server.   The value is right there on the client, there is no reason to talk to the server.   A field such as "username" may use ajax to call the server because it has to determine if the username already exists in the database, all you're doing is checking the length of the field.  javascript can do that easily (see the COBOLdinosaur's code).   Then when you submit, you check it again (see my code) using Coldfusion.

There is no benefit to taking the entries in the textarea and pushing them to the server, just to see how long it is.
Ian WhiteOwner and Founder

Author

Commented:
Thanks Ok but then how would I do this using jquery? as all the validation - messages etc use jqery and display in the modern way rather than the old school way of an alert pop up?
Sure you don't have to use pop-up, that doesn't matter.  You can populate a div with a comment, you can change the field red or whatever you want.

function testLen()  {
    if (document.getElementById('idoftextarea').innerHTML.length() < 1000)    {
       .... do whatever you want to tell the user the length is wrong ....
      return false;
    }
return true;
}

Open in new window

Ian WhiteOwner and Founder

Author

Commented:
I am sorry I just cant fit this into the current framework I have.

Here is the java script for the validation using jquery - how do I keep within this framework.
The textarea is actualy usually collapsed and only opened up when a big Plus is pressed to optionally ad description (desc) and other fields. The field in question is called desc




		// Owner Registration Form Validation
		$('#owner-reg-form').validate({
			ignore: '.noValidation *',
			rules: {
				co: 'required',
				sta: 'required',
	//			cd: 'required',
				ci: 'required',
	//			su: 'required',
				cta: 'required',
				FirstName: {
					required: true,
					maxlength: 30
				},
				LastName: {
					required: true,
					maxlength: 30
				},
				EmailAddress: {
					required: true,
					email: true,
					remote: 'ajax/email.cfc?method=chkEmail'
				},
					ConfirmEmailAddress: {
					required: true,					
					equalTo: '#EmailAddress'
				},
					UserName: {
					required: true,
					regex: '^[A-Za-z0-9_]{6,20}$',
					remote: 'ajax/username.cfc?method=chkUsername'
				},
				ChosenPassword: {
					required: true,
					regex: '^[A-Za-z0-9]{6,8}$'
				},
				ConfirmChosenPassword: {
					required: true,					
					equalTo: '#ChosenPassword'
				},
				title: 'required',
				desc: 'required',
				from: 'required',
				duration: 'required',
				HouseSitTerm: {
					required: function(element) {
						return $('#HouseSitTerm').val() == '';
					}
				},
				PetType: {
					required: function(element) {
						return $('#other-pets').val() == '';
					}
				},
				source: 'required',
				breeds: 'required',
				ConditionsAccepted: 'required'
			},
			messages: {
			  co: 'Please select a country',
			  sta: 'Please select a state',
			  cd: 'Please enter a region/county name',
			  ci: 'Please enter your city or Town, if rural closest Town',
			  su: 'Please enter a suburb name',
			  cta: 'Please enter a area name',
			  FirstName: {
					required: 'Please enter your first name',
					maxlength: 'No more than 30 characters'
				},
				LastName: {
					required: 'Please enter your last name',
					maxlength: 'No more than 30 characters'
				},
				EmailAddress: {
					required: 'Please enter an email address',
					email: 'Please enter a valid email address',
					remote: 'This email is already registered'
				},
				ConfirmEmailAddress: {
					required: 'Please confirm your email address',	
					equalTo: 'Please enter the same email address as above'
				},
				UserName: {
					required: 'Please enter a username',
					regex: 'Please enter a valid username',
					remote: 'The usename has been used'
				},
				ChosenPassword: {
					required: 'Please enter a password',
					regex: 'Please enter a valid password'
				},
				ConfirmChosenPassword: {
					required: 'Please confirm your password',
					equalTo: "Please enter the same password as above"
				},
				title: 'Please enter your title',
				desc: 'Please enter your description',
				from: 'Please select a date',
				duration: 'Please enter a duration',
				HouseSitTerm: 'Please select a House Sit Term',
				PetType: 'Please either select a pet type or specify one below',
				source: 'Please select one item',
				breeds: 'Please enter breed(s)',
				ConditionsAccepted: 'Please accept terms & conditions'
			}
		});
		
		
		// test length to ad description

Open in new window

AveAgo, checking the length of a field is really a trivial task, very similar to checking if the field is empty or populated.   If you are using a framework that you don't understand well enough to add such a test, may want to consider a different one.

I can see how you have tests to ensure the field is populated and has a max length..

FirstName: {
      required: true,
      maxlength: 30
      },

In your case, it seems you want to add a "minlength" feature instead of maxlength

The code you show does not include how it processes the keywords such as required and maxlength.  That must be somewhere else.  You have to create minlength and go into the function that processes these rules and add something to handle it.

An alternative may be to use the existing regular expression, like the one shown here...

ChosenPassword: {
      required: true,
      regex: '^[A-Za-z0-9]{6,8}$'
},


Maybe you can come up with a regular expression that will not succeeed if the text length is not long enough.  That may be your easiest way around the problem of not having a minlength rule...
Ian WhiteOwner and Founder

Author

Commented:
Ok Thanks

Does anyone know regex  for checking minimum length of text entered in a textarea. I have found various expressions in google search - but none of them work
well u can do with simple javascript, why regex - i suppose u only want to use regex where you want to allow only alpha characters followed by space
Ian WhiteOwner and Founder

Author

Commented:
The designers have deliered in the structure above which uses html5  css and modern standards.  How do I trigger this java script using this format.
Ian WhiteOwner and Founder

Author

Commented:
This worked (jquery)

                        desc: {
                        required: true,
                        minlength: 180
                        },

However I got the default jquery message

Please enter at least 180 characters.

Rather than the custom  message below:
      messages: {

            Desc: {
            required: 'Please enter your description',
            minlength: 'Please add at least 3 lines'
                                         },
Check your syntax, look for missing comma, end quote or whatever.  If that doesn't fix it it, you'll have to debug your "validate()" function...
Ian WhiteOwner and Founder

Author

Commented:
This is a know problem with jquery - not sure if any jquery experts know the solution?
perhaps this is the problem...


you're using lower case letters here..

   desc: {
                        required: true,
                        minlength: 180
                        },



and upper case "D" here....

            Desc: {
              required: 'Please enter your description',
              minlength: 'Please add at least 3 lines'
                                         },
Ian WhiteOwner and Founder

Author

Commented:
Thanks - that worked changing case to desc

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial