Validating Textareas

Welcome to our free JavaScript tutorial. This tutorial is based on Webucator's Introduction to JavaScript Training course.

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=1, 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" id="requests" cols="40" rows="6" wrap="virtual"></textarea>
	</p>
	
---- C O D E   O M I T T E D ----

Next

This tutorial is based on Webucator's Introduction to JavaScript Training Course. We also offer many other JavaScript Training courses. Sign up today to get help from a live instructor.