« Notes kill script | Main| DB2 and Domino - Mini Survival Guide »

Limit Field Length with HTML and JavaScript

Category
Bookmark : del.icio.us  Technorati  Digg This  Add To Furl  Add To YahooMyWeb  Add To Reddit  Add To NewsVine 

Quite often it's important to limit the length of characters a user can input into a field. The reasons are various and sometimes obvious, so just a quick outline here:
  • Prevent an overflow in the backend table (that would be nice!)
  • Prevent Casual testers (ie hacker novices) from entering long junk data to see if you did your homework.
  • Provide the user with a guide as to how long a field is allowed to be and how many characters they have left <- the cool bit

My solution:

  1. Javascript function to inform the user of the current length and maximum length of the field, and also to truncate the field if they reach the maximum.
  2. HTML tag to enforce a maximum length, in case javascript is not available
  3. Backend validation to ensure man-in-the-middle attacks cannot occur (this is a puritan measure, overrkill for small-scale or corporate applications. Yes I happly welcome and invite your scorn).

In the example below, a text-area field is limited by the browser to 500 characters. With every character entered, the updateCounter(element, max) function is called which checks the length of it's parent field (specified by 'the this' identifier). If the length is OK, the function looks for an element to drop information into. In this case I've added an empty SPAN who's id is the name of the field being checked with '-counter' appended. The span gets populated with information for the user. If the length is OK, the current length and the maximum length are shown in green, otherwise in red.

The Code
<html>
<head>
<script type="text/javascript">
function updateCounter (el, max) {
var span = document.getElementById (el.name + "-counter");
var str = el.value;
if (str.length >= max) {
el.value = str.substring (0,max)
span.innerHTML = "<font color=red>length: " + el.value.length + " max: " + max +"</font>"
} else {
span.innerHTML = "<font color=green>length: " + el.value.length + " max: " + max +"</font>"
}
}
</script>
</head>
<body>
<div>Enter a Description:</div>
<textarea MAXLENGTH=500 name="Description" onkeydown="updateCounter (this, 500)"></textarea>
<span id="Description-counter"></span>

Post A Comment

:-D:-o:-p:-x:-(:-):-\:angry::cool::cry::emb::grin::huh::laugh::lips::rolleyes:;-)

Calendar