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.