1

I would like to know, how can we validate the data, we can not get the data more than 20 lines using Textarea. we just want to validate the textarea with the help of Jquery. Please suggest me, the proper way for validating the values.

matino
  • 17,199
  • 8
  • 49
  • 58
PPS
  • 542
  • 1
  • 8
  • 25
  • lines? they depends on the width of the textarea..how many characters do you have in one line? Count the number of characters (instead of lines) and it becomes way easier (and avoid people extending to full page their textarea and write how much they want) – Damien Pirsy Nov 16 '11 at 09:11
  • Wow - that's going to be tricky, especially on browsers where you can resize the textarea. – Angry Dan Nov 16 '11 at 09:11
  • why are "lines" the limit for validation? shouldn't it be characters? if not then you can only either count the number of line breaks or divide the total character number by a fixed amount to get a rough estimate of lines – Liviu T. Nov 16 '11 at 09:12
  • 1
    Might be a duplicate question [Finding No of lines in textarea][1] [1]: http://stackoverflow.com/questions/3697096/finding-number-of-lines-in-an-html-textarea – Akhil Thayyil Nov 16 '11 at 09:13
  • Either change the rule so it checks characters, or disable resize on your textarea. If you do the latter, you know the number of characters per line (cols). Get the length of the string in the textarea, divide by cols and you have number of lines – Ayush Nov 16 '11 at 09:34

2 Answers2

3

Something like this, which has a maximum number of rows = 3

$("textarea").keydown(function(e){
   var rows = $(this).val().split("\n").length;
   if( e.which == 13 && rows == 3 )
   {
        alert( "TO MANY ROWS");
        return false;
   }
});

This does not check if there are to many characters in the textarea to see if there are more new rules then just enters used.

Live example: http://jsfiddle.net/hXjtv/

To call it as a function

function checkTextareaLength()
{
   var rows = $("textarea").val().split("\n").length;
   if( rows > 3 )
   {
        alert( "TO MANY ROWS");
        return false;
   }
}

The onsubmit will be something `onsubmit="checkTextareaLength();"

Niels
  • 48,601
  • 4
  • 62
  • 81
  • where we put the name of the textarea. – PPS Nov 16 '11 at 09:35
  • $("textarea[name='YOURNAME']") – Niels Nov 16 '11 at 09:38
  • 1
    This code does not handle if the user is writing a long string without pressing the enter key. – Challe Nov 16 '11 at 09:41
  • This code will check it each time a user pressed a key within the textarea, so you shouldn need to check this onsubmit. If you want to do that you need to make a function of it. Updated my example. – Niels Nov 16 '11 at 09:45
1

I have not tried it but you could try this jQuery plugin. It claims it can detect wrapped lines, unlike the code posted by Niels

Challe
  • 866
  • 12
  • 26