JSFiddle - React, Tailwind, and code Playground
HTML
<textarea id="myTextarea">fooooooooooooo bar
doooooooooooooo
mdddddddddddddddddddddddddWWWWWWWWWWWWWW</textarea><br />
The previous text area may not exceed 3 lines.<br />
<a href="http://stackoverflow.com/questions/7519337/given-a-textarea-is-there-a-way-to-restrict-length-based-on-of-lines/7521855#7521855">Part of answer at Stack Overflow</a>
CSS
#myTextarea{
width: 400px;
height: 200px;
}
JavaScript
(function(){
var wordWidthMappers = {};
function checkHeight(textarea, maxLines){
if(!(textarea instanceof $)) return; /*JQuery is required*/
if(isNaN(maxLines) || !isFinite(maxLines) || maxLines == 0) return;
var areaWidth = textarea.width();
var oldHeight = textarea.css("height");
var oldOverflow = textarea.css("overflow-y");
var lineHeight = parseFloat(textarea.css("line-height"));
var maxTxtHeight = maxLines*lineHeight + "px";
/*Calculations for an efficient determination*/
var fontstyles = "font-size:"+textarea.css("font-size");
fontstyles += ";font-family:"+textarea.css("font-family");
fontstyles += ";font-weight:"+textarea.css("font-weight");
fontstyles += ";font-style:"+textarea.css("font-style");
fontstyles += ";font-variant:"+textarea.css("font-variant");
var wordWidth = wordWidthMappers[fontstyles];
if(!wordWidth){
var span = document.createElement("span");
span.style.cssText = fontstyles+";display:inline;width:auto;min-width:0;padding:0;margin:0;border:none;";
span.innerHTML = "W"; //Widest character
document.body.appendChild(span);
wordWidth = wordWidthMappers[fontstyles] = $(span).width();
document.body.removeChild(span);
}
textarea = textarea[0];
var temparea = textarea.cloneNode(false);
temparea.style.visibility = "hidden";
temparea.style.height = maxTxtHeight;
temparea.value = textarea.value;
document.body.appendChild(temparea);
/*Math.round is necessary, to deal with browser-specific interpretations
of height*/
if(Math.round(temparea.scrollHeight/lineHeight) > maxLines){
textarea.value = "";
...