Block enter if textarea is empty

Asked

Viewed 424 times

0

I’m trying to check if a textarea has valid text. Checking the space was easy, but the enter I don’t know how to check.

enviar() {
    var num = 13; // 13 é o cód ascii do enter
    if (this.textoEmEdicao == '' || this.textoEmEdicao === " ") { // verifico se o texto é nulo ou tem espaço
      this.textoEmEdicao = '';// setar a textbox para nenhum texto
    } else {
      let mensagem = {
        texto: this.textoEmEdicao,
        data: new Date(),
        contato: this.emissor
      }
      this.adicionarMensagem(mensagem);
      this.textoEmEdicao = '';
    }
}
  • I believe that the question is not to block Enter. You want to block Enter for what reason? What this function enviar() ago?

3 answers

2

Use preventDefault

Definition and Use

The preventDefault() method cancels the event if it is cancellable, which means that the default action belonging to the event will not occur.

For example, this can be useful when:

  • By clicking on a "Submit" button, prevent it from sending a form
  • Clicking on a link prevents the link from following the URL

Note: not all events are cancellable. Use property cancelable to find out if an event is cancellable.

Note: The preventDefault() method does not prevent further propagation of an event through the DOM. Use the stopPropagation() method to handle thereby.

Source: W3schools

Example:

function blockEvent(e) {
  var code = (e.keyCode ? e.keyCode : e.which);
  if (code == 13 && document.getElementById("txt").value === "") {
    e.preventDefault();
  }
}
<textarea id="txt" cols="40" rows="5" onkeypress="blockEvent(event, this)"></textarea>

0

If you want to know textarea contains only spaces it is better to just use the function String.trim and check that it is not empty.

The trim removes any white space from the beginning and end of a string, be it line breaks, tabs, spaces, etc...

let text = document.getElementById('teste');
let feedback = document.getElementById('feedback');

text.addEventListener('keyup', function (event) {
  // retira todos os espaços do início e do fim
  let trimmed = this.value.trim();
  
  // se for vazio mostra erro e apaga o conteúdo.
  if (!trimmed) {
    this.value = '';
    feedback.innerHTML = "textarea vazio";
  } else {
    // se estiver OK remove o erro
    feedback.innerHTML = "";
  }
});
#teste {
  width: 100%;
  height: 100px;
  resize: vertical;
}
<textarea id="teste"></textarea>
<span id="feedback"></span>

0


To verify can use regex /\S/.test(textarea)

To block can use @fernandosavio’s reply

1 - empty

var textarea=document.getElementById("demo").value;

if(/\S/.test(textarea)) {
   console.log('valido');
}else{
   console.log('não válido');
}
<textarea id='demo'></textarea>

2 - with space

    var textarea=document.getElementById("demo").value;

    if(/\S/.test(textarea)) {
       console.log('valido');
    }else{
       console.log('não válido');
    }
<textarea id='demo'> </textarea>

3 - with line break

     var textarea=document.getElementById("demo").value;

     if(/\S/.test(textarea)) {
        console.log('valido');
     }else{
        console.log('não válido');
     }
<textarea id='demo'> 


</textarea>

4- with some content

     var textarea=document.getElementById("demo").value;

     if(/\S/.test(textarea)) {
        console.log('valido');
     }else{
        console.log('não válido');
     }
        <textarea id='demo'>
        
        x 


        </textarea>

/\S/.test(textarea) returns true if and only if there is a non-space character

  • Thank you very much, it was exactly what I needed, you still managed to gather all the answers in one, will save time many people, congratulations!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.