Harshitha Kumar Harshitha Kumar - 8 months ago 53
Javascript Question

Javascript for validating Multiline Text area's input characters

I have a multiline text area which accepts 42 characters and if the user exceeds the limit and clicks on submit button, he will get a alert message like 'exceeded the limit so remove '***' characters. Below is the code which performs the same.

<head runat="server">
<script type="text/javascript">
function ok(maxchars) {
if (document.ourform.box.value.length > maxchars) {
alert('Too much data in the text box! Please remove ' +
(document.ourform.box.value.length - maxchars) + ' characters');
return false;
return true;
<form action="http://www.cs.tut.fi/cgi-bin/run/~jkorpela/chkarea.pl"
method="post" name="ourform" onsubmit="return ok(42)">
Please enter data, at most 42 characters:<br/>
<textarea name="box" rows="5" cols="30">
<br/><input type="submit"/>

But my problem is I should get the same alert message once I de-focus the control from the text box area instead of clicking on submit button.
So Please help me for achieving it...!!
Thanks in advance...

Additional requirement: After getting the alert message and clicking on ok button,the extra characters should be deleted. Please help..


Here is a simple solution using jQuery

  	if($(this).val().length > $(this).data("limit") - 1) {
			alert("You have reached the limit");
  		return false;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" name="ourform">
  Please enter data, at most 42 characters:<br/>
  <textarea name="box" rows="5" cols="30" data-limit="10" id="box">
  <br/><input type="submit"/>

Please try this.