Validating Textareas

Contact Us or call 1-877-932-8228
Validating Textareas

Validating Textareas

Textareas can be validated the same way that text fields are by using the checkLength() function shown earlier. However, because textareas generally allow for many more characters, it's often difficult for the user to know if he's exceeded the limit. It could be helpful to let the user know if there's a problem as soon as focus leaves the textarea. The example below, which contains a more complete form for ordering ice cream, includes a function that alerts the user if there are too many characters in a textarea.

Code Sample:

FormValidation/Demos/IceCreamForm.html
---- C O D E   O M I T T E D ----
function checkLength(text, min, max){
	min = min || 1;
	max = max || 10000;
	if (text.length < min || text.length > max) {
		return false;
	}
	return true;
}

function checkTextArea(textArea, max){
	var numChars, chopped, message;
	if (!checkLength(textArea.value, 0, max)) {
		numChars = textArea.value.length;
		chopped = textArea.value.substr(0, max);
		message = 'You typed ' + numChars + ' characters.\n';
		message += 'The limit is ' + max + '.';
		message += 'Your entry will be shortened to:\n\n' + chopped;
		alert(message);
		textArea.value = chopped;
	}
}

---- C O D E   O M I T T E D ----

	<p>
	<strong>Special Requests:</strong><br>
	<textarea name="requests" cols="40" rows="6" wrap="virtual"
		onblur="checkTextArea(this, 100);"></textarea>
	</p>
---- C O D E   O M I T T E D ----
Next