Validating text box

Asked

Viewed 1,645 times

1

Whenever I do a javascript validation of a text box, to know if it is empty or not, I do it as follows:

function validar(){
    var input = document.getElementById("texto");
    if(input.value == ""){

         alert("Preencha todos os campos em branco.")

    }
}

However, today I discovered that this has a fault if the user leaves in the text box a space like this:

inserir a descrição da imagem aqui

... and validate the form will not recognize as empty.

Although it is possible to do this:

function validar(){
    var input = document.getElementById("texto");
    if((input.value == "") || (input.value == " ")){
         alert("Preencha todos os campos em branco.")
    }
}

.. and knowing that there are these amazing solutions, I need to know if it is possible to verify if there are any characters inside the text box. And a way to do it in pure javascript.

  • A space is a character, as well as a . e , which by their verification would be valid. It would be more interesting to use a validation rule or define a minimum number of char.

1 answer

1


To not accept blank spaces, that pass on the line I suggested above can use /^\s*$/.test(input.value);. This regular expression will look for blanks 1 or more times and test the input to see if it is empty. Gives true if it is empty.

Example: http://jsfiddle.net/9Thp6/1/


If you want to be rigid you can use (input.valuelength + '') == 0. So check if the input is really empty. Here blanks are accepted.

  • 1

    You can show me a functional example of this?

  • 1

    I put together an example to test.

Browser other questions tagged

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