How to check variables with jQuery so they are not sent empty?

2

I'm learning about jQuery and I've already started doing Ajax requests to register the information in the mysql database. I have a code that has several variables and I would like to ask how I can check at one time if there is any empty variable. I was thinking of doing this with array but I do not know how to use it. These variables will be captured from the submit form. I ask for help!

    var empresa;        
    var username;       
    var ativado;            
    var tipousuario;        
    var senha;              
    var nome;               
    var cpf;                
    var cnpj;               
    
asked by anonymous 07.08.2014 / 03:06

1 answer

1

Sometimes client-side and server-side validation is done. There are always several ways you can do it.

To do a check on the client side you will have to search for element.value , element.checked depending on the element type, and in case input type="radio" has to go through all of them and see if one of them is selected. It may facilitate a bit by joining a class to these elements, but otherwise test like this:

var validado = true, erros = 0;
$('input, select, textarea').each(function () {
    var nomeTag = this.tagName.toLowerCase()
    if (nomeTag == 'select' || nomeTag == 'textarea') validado = !!this.value;
    else if (this.type == 'checkbox') validado = !!this.checked;
    else if (this.type == 'radio') validado = !!$('input').filter(function () {
        return this.checked
    })[0];
    else validado = !!this.value

    if (!validado) {
        this.addClass('incompleto');
        erros++;
    } else {
        this.removeClass('incompleto');
    }
});
if (erros) // validacao falhou!

If erros does not give 0 after this code then there are empty fields. I put together an optional part to give a class the empty elements for user visibility.

On the PHP side all fields go inside $ _GET or $ _POST, it depends how you are using it. Here you can do a simple check with a for loop:

foreach ($post as $chave=>$valor) if (!$valor) die('O campo '.$chave.' está  vazio!');

There are more complex methods for checking the content type. In these examples, and in the sequence of what you asked, this only checks for empty fields.

Attention: this check does nothing to make content safe, ie this check must follow another one that prepares the content to be inserted into the database.

    
07.08.2014 / 08:20