Validating text box

1

Always when I do a javascript validation of a text box, to see 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 flaw, if the user leaves a space like this in the text box:

...andvalidatetheformwillnotrecognizeitasempty.

Whileitmightbepossibletodothis:

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

.. And knowing that there are such cool solutions, I need to know if you can check for any characters inside the text box. And a way to do it in pure javascript.

    
asked by anonymous 01.08.2014 / 23:57

1 answer

1

Not to accept whitespaces, which pass on the line I suggested above you can use /^\s*$/.test(input.value); . This regular expression will search for blanks 1 or more times and test the input to see if it is empty. It gives true if it is empty.

Example: link

If you want to be hard, you can use (input.valuelength + '') == 0 . This checks to see if the input is empty. Here blanks are accepted.

    
02.08.2014 / 00:09