Você está aqui: JavaScript ::: Dicas & Truques ::: Validação de Formulários |
Validar CPF (sem pontos e hífen)Quantidade de visualizações: 16572 vezes |
<html> <head> <title>Estudando JavaScript</title> <script language="JavaScript"> function validarCPF(){ var cpf = document.cadastro.cpf.value; if(cpf.length != 11 || cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999"){ window.alert("CPF inválido. Tente novamente."); return false; } soma = 0; for(i = 0; i < 9; i++) soma += parseInt(cpf.charAt(i)) * (10 - i); resto = 11 - (soma % 11); if(resto == 10 || resto == 11) resto = 0; if(resto != parseInt(cpf.charAt(9))){ window.alert("CPF inválido. Tente novamente."); return false; } soma = 0; for(i = 0; i < 10; i ++) soma += parseInt(cpf.charAt(i)) * (11 - i); resto = 11 - (soma % 11); if(resto == 10 || resto == 11) resto = 0; if(resto != parseInt(cpf.charAt(10))){ window.alert("CPF inválido. Tente novamente."); return false; } return true; } </script> </head> <body> <form name="cadastro" onSubmit="return validarCPF()"> Informe seu CPF (use os pontos e o hífen):<br> <input type="text" maxlength="14" name="cpf"> <input type="submit" value="Enviar!"> </form> </body> </html> |
![]() |
Desafios, Exercícios e Algoritmos Resolvidos de JavaScript |
Veja mais Dicas e truques de JavaScript |
Dicas e truques de outras linguagens |
E-Books em PDF |
||||
|
||||
|
||||
Linguagens Mais Populares |
||||
1º lugar: Java |