Estou fazendo a validação do formulário e estava tudo funcionando, mas ao inserir o campo idade, o checkbox começou a passar direto sem validar. Pois se eu não preencher nenhum checkbox o js deveria retornar uma mensagem com o alert. Vou postar o código. Se alguém puder me ajudar a achar o erro.
[code]
Cadastro de Hobbies
.borda {
border: thin solid #000;
}
Nome
Endereço
Sexo
Masculino
Feminino
Estado Civil
--------------------------
Solteiro(a)
Casado(a)
Viúvo(a)
Divorciado(a)
Separado(a) judicialmente
Data de Nascimento
Hobbies
<tr>
<td><label>
<input type="checkbox" name="chk_hobbies[]" value="1" id="chk_hobbies_0" />
Esporte</label></td>
<td><label>
<input type="checkbox" name="chk_hobbies[]" value="2" id="chk_hobbies_1" />
Jardinagem</label></td>
</tr>
<tr>
<td><label>
<input type="checkbox" name="chk_hobbies[]" value="3" id="chk_hobbies_2" />
Pintura</label></td>
<td><label>
<input type="checkbox" name="chk_hobbies[]" value="4" id="chk_hobbies_3" />
Corte & Custura</label></td>
</tr>
<tr>
<td><label>
<input type="checkbox" name="chk_hobbies[]" value="5" id="chk_hobbies_4" />
Musica</label></td>
<td><label>
<input type="checkbox" name="chk_hobbies[]" value="6" id="chk_hobbies_5" />
Meditação</label></td>
</tr>
<tr>
<td><label>
<input type="checkbox" name="chk_hobbies[]" value="7" id="chk_hobbies_6" />
Leitura</label></td>
<td><label>
<input type="checkbox" name="chk_hobbies[]" value="8" id="chk_hobbies_7" />
Jogos Eletrônicos</label></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="button" name="btn_addhoobies" id="btn_addhoobies" value="Adicionar Hobbies" /></td>
</tr>
</table></td>
</tr>
Comente um pouco sobre você
[/code]
Ainda tenho mais validações para inserir, e tenho que fazer o mesmo com php, por isso preciso achar o erro. Estou a três dias tentando e nada.
Quando eu retiro as funções do checkbok aí tudo funciona certinho.
Arrumei o codigo para voce.
Primeiro, o nome dos checkboxes estava errados vc nao precisa “[]”, segundo que no javascript, quando vc pega cara checkbox pra testar se checked == false, vc comeca do indice 1 e o correto eh 0.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Cadastro de Hobbies</title>
<style>
.borda {
border: thin solid #000;
}
</style>
<script language="javascript" >
function valida_end(form){
var padrao = /[a-z]+\s+[a-z]+/gi;
var text = document.getElementById('txt_nome');
if (!padrao.test(text.value)) {
alert("Digite Nome e Sobrenome");
form.txt_nome.focus();
return false;
}
if (form.txt_endereco.value== "" || form.txt_endereco.value.length <2) {
alert("Preencha o endereço corretamente.");
form.txt_endereco.focus();
return false;
}
if (form.rdo_sexo[0].checked==false && form.rdo_sexo[1].checked==false) {
alert("Selecione o sexo.");
return false;
}
if (form.txt_idade.value=="" ){
alert("Preencha a Idade Corretamente.");
form.txt_idade.focus();
return false;
}
if (isNaN(form.txt_idade.value)){
alert("Preencha Com Números Inteiros.");
form.txt_idade.focus();
return false;
}
else if((form.txt_idade.value < 3 || form.txt_idade.value > 149)){
alert("Insira Uma Idade Maior que 2 e Inferior a 150.");
form.txt_idade.focus();
return false;
}
if (form.chk_hobbies[0].checked==false &&
form.chk_hobbies[1].checked==false &&
form.chk_hobbies[2].checked==false &&
form.chk_hobbies[3].checked==false &&
form.chk_hobbies[4].checked==false &&
form.chk_hobbies[5].checked==false &&
form.chk_hobbies[6].checked==false &&
form.chk_hobbies[7].checked==false){
alert("Selecione os Hobbies.");
return false;
}
var padrao2 = /[a-z]+\s+[a-z]+/gi;
var text = document.getElementById('txa_comentario');
if (!padrao2.test(text.value)) {
alert("Comente um pouco sobre você!");
form.txa_comentario.focus();
return false;
}
}
</script>
</head>
<body>
<form name="frmhobbie" onsubmit=" return valida_end(this)" method="post" action="">
<form name="frmhobbie" method="post" action="">
<table width="366" align="left" class="borda" cellpadding="0" cellspacing="0" border="1">
<tr>
<td width="121"><label for="txt_nome">Nome</label></td>
<td width="194"><input type="text" name="txt_nome" id="txt_nome" valeu=""/></td>
</tr>
<tr>
<td><label for="txt_endereco">Endereço</label></td>
<td><input type="text" name="txt_endereco" id="txt_endereco" value="" /></td>
</tr>
<tr>
<td><label for="rdo_sexo_0">Sexo</label></td>
<td><p>
<label>
<input type="radio" name="rdo_sexo" value="M" id="rdo_sexo_0" />
Masculino</label>
<br />
<label>
<input type="radio" name="rdo_sexo" value="F" id="rdo_sexo_1" />
Feminino</label>
<br />
</p></td>
</tr>
<tr>
<td><label for="slt_civil">Estado Civil</label></td>
<td>
<select name="slt_civil" id="slt_civil">
<option value="">--------------------------</option>
<option value="S">Solteiro(a)</option>
<option value="C">Casado(a)</option>
<option value="V">Viúvo(a)</option>
<option value="D">Divorciado(a)</option>
<option value="J">Separado(a) judicialmente </option>
</select>
</td>
</tr>
<tr>
<td><label for="txt_idade">Data de Nascimento</label></td>
<td><input type="text" name="txt_idade" id="txt_idade" value="" maxlength="10" size="12" /></td>
</tr>
<tr>
<td colspan="2">Hobbies</td>
</tr>
<tr>
<td colspan="2"><table width="100%">
<tr>
<td><label>
<input type="checkbox" name="chk_hobbies" value="1" id="chk_hobbies_0" />
Esporte</label></td>
<td><label>
<input type="checkbox" name="chk_hobbies" value="2" id="chk_hobbies_1" />
Jardinagem</label></td>
</tr>
<tr>
<td><label>
<input type="checkbox" name="chk_hobbies" value="3" id="chk_hobbies_2" />
Pintura</label></td>
<td><label>
<input type="checkbox" name="chk_hobbies" value="4" id="chk_hobbies_3" />
Corte & Custura</label></td>
</tr>
<tr>
<td><label>
<input type="checkbox" name="chk_hobbies" value="5" id="chk_hobbies_4" />
Musica</label></td>
<td><label>
<input type="checkbox" name="chk_hobbies" value="6" id="chk_hobbies_5" />
Meditação</label></td>
</tr>
<tr>
<td><label>
<input type="checkbox" name="chk_hobbies" value="7" id="chk_hobbies_6" />
Leitura</label></td>
<td><label>
<input type="checkbox" name="chk_hobbies" value="8" id="chk_hobbies_7" />
Jogos Eletrônicos</label></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="button" name="btn_addhoobies" id="btn_addhoobies" value="Adicionar Hobbies" /></td>
</tr>
</table></td>
</tr>
<tr>
<td colspan="2"><label for="txa_comentario">Comente um pouco sobre você</label></td>
</tr>
<tr>
<td colspan="2"><textarea rows="5" cols="50" name="txa_comentario" id="txa_comentario"></textarea></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="sbm_enviar" id="sbm_enviar" value="Enviar" /> <input type="reset" name="rst_limpar" id="rst_limpar" value="Limpar" /></td>
</tr>
</table>
</form>
</body>
</html>
PS: Arruma, o seu codigo, coloca javascript eh um arquivo separado, funcao de validacao nao deveria mostrar mensagens de error, alerts e nada disso, deveria somente retornar, se os dados sao validos ou nao.
//Daniel
grinche
Outubro 11, 2012, 6:30am
#3
Acho muito interessante você pensar em utilizar uma biblioteca javascript em seus projetos.
Utilizei JQuery no código abaixo, veja o quanto o código fica simples.
E JQuery hoje é utilizado pela maioria dos desenvolvedores web então seu código se torna de facil manutenção.
var checkBoxMarcados = $("input:checkbox").is(':checked').size();
if (checkBoxMarcados == 0) {
alert("Selecione os Hobbies.");
}
Vou te dar uma dica que talvez tenha necessidade de você alterar algumas coisas no seu projeto, porém o resultado é muito bom!
Utilize ou Twitter Bootstrap ou Primefaces.
Até!
[quote=Kuster_01]Estou fazendo a validação do formulário e estava tudo funcionando, mas ao inserir o campo idade, o checkbox começou a passar direto sem validar. Pois se eu não preencher nenhum checkbox o js deveria retornar uma mensagem com o alert. Vou postar o código. Se alguém puder me ajudar a achar o erro.
[code]
Cadastro de Hobbies
.borda {
border: thin solid #000;
}
Nome
Endereço
Sexo
Masculino
Feminino
Estado Civil
--------------------------
Solteiro(a)
Casado(a)
Viúvo(a)
Divorciado(a)
Separado(a) judicialmente
Data de Nascimento
Hobbies
<tr>
<td><label>
<input type="checkbox" name="chk_hobbies[]" value="1" id="chk_hobbies_0" />
Esporte</label></td>
<td><label>
<input type="checkbox" name="chk_hobbies[]" value="2" id="chk_hobbies_1" />
Jardinagem</label></td>
</tr>
<tr>
<td><label>
<input type="checkbox" name="chk_hobbies[]" value="3" id="chk_hobbies_2" />
Pintura</label></td>
<td><label>
<input type="checkbox" name="chk_hobbies[]" value="4" id="chk_hobbies_3" />
Corte & Custura</label></td>
</tr>
<tr>
<td><label>
<input type="checkbox" name="chk_hobbies[]" value="5" id="chk_hobbies_4" />
Musica</label></td>
<td><label>
<input type="checkbox" name="chk_hobbies[]" value="6" id="chk_hobbies_5" />
Meditação</label></td>
</tr>
<tr>
<td><label>
<input type="checkbox" name="chk_hobbies[]" value="7" id="chk_hobbies_6" />
Leitura</label></td>
<td><label>
<input type="checkbox" name="chk_hobbies[]" value="8" id="chk_hobbies_7" />
Jogos Eletrônicos</label></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="button" name="btn_addhoobies" id="btn_addhoobies" value="Adicionar Hobbies" /></td>
</tr>
</table></td>
</tr>
Comente um pouco sobre você
[/code]
Ainda tenho mais validações para inserir, e tenho que fazer o mesmo com php, por isso preciso achar o erro. Estou a três dias tentando e nada.
Quando eu retiro as funções do checkbok aí tudo funciona certinho.[/quote]
Primeiramente obrigado por acertar o código. Mas tenho mais uma pergunta: É possível fazer essas validações do checkbox com javascript utilizando os colchetes como estava no código?
[quote=windsofhell]
Arrumei o codigo para voce.
Primeiro, o nome dos checkboxes estava errados vc nao precisa “[]”, segundo que no javascript, quando vc pega cara checkbox pra testar se checked == false, vc comeca do indice 1 e o correto eh 0.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Cadastro de Hobbies</title>
<style>
.borda {
border: thin solid #000;
}
</style>
<script language="javascript" >
function valida_end(form){
var padrao = /[a-z]+\s+[a-z]+/gi;
var text = document.getElementById('txt_nome');
if (!padrao.test(text.value)) {
alert("Digite Nome e Sobrenome");
form.txt_nome.focus();
return false;
}
if (form.txt_endereco.value== "" || form.txt_endereco.value.length <2) {
alert("Preencha o endereço corretamente.");
form.txt_endereco.focus();
return false;
}
if (form.rdo_sexo[0].checked==false && form.rdo_sexo[1].checked==false) {
alert("Selecione o sexo.");
return false;
}
if (form.txt_idade.value=="" ){
alert("Preencha a Idade Corretamente.");
form.txt_idade.focus();
return false;
}
if (isNaN(form.txt_idade.value)){
alert("Preencha Com Números Inteiros.");
form.txt_idade.focus();
return false;
}
else if((form.txt_idade.value < 3 || form.txt_idade.value > 149)){
alert("Insira Uma Idade Maior que 2 e Inferior a 150.");
form.txt_idade.focus();
return false;
}
if (form.chk_hobbies[0].checked==false &&
form.chk_hobbies[1].checked==false &&
form.chk_hobbies[2].checked==false &&
form.chk_hobbies[3].checked==false &&
form.chk_hobbies[4].checked==false &&
form.chk_hobbies[5].checked==false &&
form.chk_hobbies[6].checked==false &&
form.chk_hobbies[7].checked==false){
alert("Selecione os Hobbies.");
return false;
}
var padrao2 = /[a-z]+\s+[a-z]+/gi;
var text = document.getElementById('txa_comentario');
if (!padrao2.test(text.value)) {
alert("Comente um pouco sobre você!");
form.txa_comentario.focus();
return false;
}
}
</script>
</head>
<body>
<form name="frmhobbie" onsubmit=" return valida_end(this)" method="post" action="">
<form name="frmhobbie" method="post" action="">
<table width="366" align="left" class="borda" cellpadding="0" cellspacing="0" border="1">
<tr>
<td width="121"><label for="txt_nome">Nome</label></td>
<td width="194"><input type="text" name="txt_nome" id="txt_nome" valeu=""/></td>
</tr>
<tr>
<td><label for="txt_endereco">Endereço</label></td>
<td><input type="text" name="txt_endereco" id="txt_endereco" value="" /></td>
</tr>
<tr>
<td><label for="rdo_sexo_0">Sexo</label></td>
<td><p>
<label>
<input type="radio" name="rdo_sexo" value="M" id="rdo_sexo_0" />
Masculino</label>
<br />
<label>
<input type="radio" name="rdo_sexo" value="F" id="rdo_sexo_1" />
Feminino</label>
<br />
</p></td>
</tr>
<tr>
<td><label for="slt_civil">Estado Civil</label></td>
<td>
<select name="slt_civil" id="slt_civil">
<option value="">--------------------------</option>
<option value="S">Solteiro(a)</option>
<option value="C">Casado(a)</option>
<option value="V">Viúvo(a)</option>
<option value="D">Divorciado(a)</option>
<option value="J">Separado(a) judicialmente </option>
</select>
</td>
</tr>
<tr>
<td><label for="txt_idade">Data de Nascimento</label></td>
<td><input type="text" name="txt_idade" id="txt_idade" value="" maxlength="10" size="12" /></td>
</tr>
<tr>
<td colspan="2">Hobbies</td>
</tr>
<tr>
<td colspan="2"><table width="100%">
<tr>
<td><label>
<input type="checkbox" name="chk_hobbies" value="1" id="chk_hobbies_0" />
Esporte</label></td>
<td><label>
<input type="checkbox" name="chk_hobbies" value="2" id="chk_hobbies_1" />
Jardinagem</label></td>
</tr>
<tr>
<td><label>
<input type="checkbox" name="chk_hobbies" value="3" id="chk_hobbies_2" />
Pintura</label></td>
<td><label>
<input type="checkbox" name="chk_hobbies" value="4" id="chk_hobbies_3" />
Corte & Custura</label></td>
</tr>
<tr>
<td><label>
<input type="checkbox" name="chk_hobbies" value="5" id="chk_hobbies_4" />
Musica</label></td>
<td><label>
<input type="checkbox" name="chk_hobbies" value="6" id="chk_hobbies_5" />
Meditação</label></td>
</tr>
<tr>
<td><label>
<input type="checkbox" name="chk_hobbies" value="7" id="chk_hobbies_6" />
Leitura</label></td>
<td><label>
<input type="checkbox" name="chk_hobbies" value="8" id="chk_hobbies_7" />
Jogos Eletrônicos</label></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="button" name="btn_addhoobies" id="btn_addhoobies" value="Adicionar Hobbies" /></td>
</tr>
</table></td>
</tr>
<tr>
<td colspan="2"><label for="txa_comentario">Comente um pouco sobre você</label></td>
</tr>
<tr>
<td colspan="2"><textarea rows="5" cols="50" name="txa_comentario" id="txa_comentario"></textarea></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="sbm_enviar" id="sbm_enviar" value="Enviar" /> <input type="reset" name="rst_limpar" id="rst_limpar" value="Limpar" /></td>
</tr>
</table>
</form>
</body>
</html>
PS: Arruma, o seu codigo, coloca javascript eh um arquivo separado, funcao de validacao nao deveria mostrar mensagens de error, alerts e nada disso, deveria somente retornar, se os dados sao validos ou nao.
//Daniel[/quote]