0

I would like to detect a new empty line in a text area and if the user just pressed enter in the text area, without entering any data to return false and echo a message. I have made some research and thought of something like this:

var validatef ....
var code = (e.keyCode ? e.keyCode : e.which);
if (validatef == 'a value here' || code == 13) { 
  somevarhere.textcontent = 'Message';
  return false;
}
else {....}

But it doesn't seem to work.

Akshaya Shanbhogue
  • 1,438
  • 1
  • 13
  • 25
Adrian
  • 2,273
  • 4
  • 38
  • 78

5 Answers5

2

You can detect an empty line in a textarea by checking for the values:

\r\n (works fine for me) or \n

Just replace the text a value here with \r\n or \n what best suits you.

EDIT:

Check How to count string occurrence in string? to count regex appearances. So you can make a for loop to show the error message on /\s/g.

Hope it helps.

Community
  • 1
  • 1
Diosney
  • 10,520
  • 15
  • 66
  • 111
1

just test if the user pressed enter twice

/\n\n/.test(this.value)
Jay Harris
  • 4,201
  • 17
  • 21
1

Try this

 $('textarea').on('keypress', function(e) {
    var val = $('textarea').val();
    if (e.which == 13) {
if(! /\S/.test(val)) {
   alert("no data");
}
    }
});

this alerts no data for each keypress.

This is in jQuery but it will be similar even in plain Javascript

Here is the demo http://jsfiddle.net/TUCx8/

Kishore
  • 1,914
  • 1
  • 15
  • 22
  • Would have been great if it was javascript don;t know how $('textarea').on('keypress', function(e) translates to javascript – Adrian Oct 25 '13 at 21:23
1

According to the first sentence of the question, this may be one of possible solutions:

var enters = 0;
$('textarea').keypress(function(event) {
    if (event.which == 13)
        enters++;
    else
        enters = 0;
    if (enters > 1) {
        alert('You hit 2 new lines!');
    }
});

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

0

Another one solution is to check an empty line right before the end of text:

(function(){
    $('textarea').keyup(function(event) {
        if (/(\r?\n){2}$/.test($(this).val())) {
            alert('2 consecutive empty lines at the end!');
        }
    });
})();

It would work independent of consecutive enter presses. http://jsfiddle.net/fp6xk/4/