Question:
I'm learning about jQuery and I've already started making Ajax requests to register the information in mysql database. I have code that has several variables and I would like to ask how I can check at once if there are any empty variables. I was thinking about doing this with array but I don't know how to use it. These variables will be captured from the form submit. I ask for help!
var empresa;
var username;
var ativado;
var tipousuario;
var senha;
var nome;
var cpf;
var cnpj;
Answer:
Sometimes client-side and server-side validation is done. There are always several ways to do this.
To do a client-side check you will have to look for element.value
, element.checked
depending on the type of element, and in the case of input type="radio"
have to go through them all and see if one of them is selected. It might make it a little easier to add a class to these elements, but otherwise test it 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 the erros
not 0
after this code then there are empty fields. Added an optional part to give a class to empty elements for user visibility.
On the PHP side all fields go inside $_GET or $_POST, it depends how you are using it. Then you can do a simple check with a for cycle:
foreach ($post as $chave=>$valor) if (!$valor) die('O campo '.$chave.' está vazio!');
There are more complex methods to check the content type. In these examples, and following what you asked, this only checks for empty fields.
Attention: this verification does nothing to make the content secure, that is, this verification must be followed by another verification that prepares the content to be inserted in the database.