Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Lisbao

Validação de CPF e CNPJ

Recommended Posts

Olá a todos!!!

eu estou fazendo uma página de validação de form!

 

Não sei usar muito javascript, na verdade naum sei qse nada, mas vi algumas coisas e adicionei ao meu site e funcionou!

agora to com outro problema!

 

A pessoa que entrar pode ou ser jurídica ou ser física:

então gostaria de fazer o seguinte, caso esteja vazio o campo cnpj, então o campo CPF está preenchido ou vice-versa, e caso os dois estejam vazios, aparece um alert!

 

eu fiz isso, por favor me ajudem nisso!

 

aqui está o código completo dessa página!

 

<html>

<head>

 

 

<script language="JavaScript" type="text/JavaScript">

<!--

function MM_findObj(n, d) { //v4.01

var p,i,x; if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {

d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}

if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[n];

for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers.document);

if(!x && d.getElementById) x=d.getElementById(n); return x;

}

 

function MM_validateForm() { //v4.0

var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;

for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args);

if (val) { nm=val.name; if ((val=val.value)!="") {

if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');

if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';

} else if (test!='R') { num = parseFloat(val);

if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';

if (test.indexOf('inRange') != -1) { p=test.indexOf(':');

min=test.substring(8,p); max=test.substring(p+1);

if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';

} } } else if (test.charAt(0) == 'R') errors += '- '+nm+' são necessários.\n'; }

} if (errors) alert('O(s) seguinte(s) erro(s) ocorreram:\n'+errors);

document.MM_returnValue = (errors == '');

}

 

 

 

function validaCPF() {

cpf = document.validacao.cpf.value;

valor = true;

erro = new String;

if (cpf.length < 11) erro += "Sao necessarios 11 digitos para verificacao do CPF! \n\n";

var nonNumbers = /\D/;

if (nonNumbers.test(cpf)) erro += "A verificacao de CPF suporta apenas numeros! \n\n";

if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999"){

erro += "Numero de CPF invalido!"

}

var a = [];

var b = new Number;

var c = 11;

for (i=0; i<11; i++){

a = cpf.charAt(i);

if (i < 9) b += (a * --c);

}

if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }

b = 0;

c = 11;

for (y=0; y<10; y++) b += (a[y] * c--);

if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }

if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10])){

erro +="Digito verificador com problema!";

}

if (erro.length > 0){

alert(erro);

return false;

}

return true;

}

 

function validaCNPJ() {

 

CNPJ = document.validacao.cnpj.value;

erro = new String;

if (CNPJ.length < 18) erro += "E' necessarios preencher corretamente o numero do CNPJ! \n\n";

if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){

if (erro.length == 0) erro += "E' necessarios preencher corretamente o numero do CNPJ! \n\n";

}

//substituir os caracteres que nao sao numeros

if(document.layers && parseInt(navigator.appVersion) == 4){

x = CNPJ.substring(0,2);

x += CNPJ.substring(3,6);

x += CNPJ.substring(7,10);

x += CNPJ.substring(11,15);

x += CNPJ.substring(16,18);

CNPJ = x;

} else {

CNPJ = CNPJ.replace(".","");

CNPJ = CNPJ.replace(".","");

CNPJ = CNPJ.replace("-","");

CNPJ = CNPJ.replace("/","");

}

var nonNumbers = /\D/;

if (nonNumbers.test(CNPJ)) erro += "A verificacao de CNPJ suporta apenas numeros! \n\n";

var a = [];

var b = new Number;

var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];

for (i=0; i<12; i++){

a = CNPJ.charAt(i);

b += a * c[i+1];

}

if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }

b = 0;

for (y=0; y<13; y++) {

b += (a[y] * c[y]);

}

if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }

if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){

erro +="Digito verificador com problema!";

}

if (erro.length > 0){

alert(erro);

return false;

}

 

return true;

}

function verifica()

{

CNPJ = document.validacao.cnpj.value;

CPF = document.validacao.CPF.value;

if(CNPJ=="")

{

if(CPF=="")

{

alert("Digite um CPF ou um CNPJ");

return false;

}

else

{

validaCPF();

}

}

else

{

validaCNPJ();

}

}

//-->

</script>

<link href="designform.css" rel="stylesheet" type="text/css">

</head>

 

<body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">

<form action="cad.php" method="post" name="validacao" id="cad_pj_corp" onsubmit="return verifica();return validaCPF();return ValidaCNPJ();MM_validateForm('razao','','R','nome_fantasia','','R','cnpj','','R','ie','','R','contato1','','R','endereco','','R','cep','','R','cidade','','R','email','','RisEmail','ddd','','RisNum','telefone','','RisNum','ramal','','RisNum');return document.MM_returnValue">

<table width="100%" border="1" cellspacing="0" id="estilo">

<tr>

<td width="19%">Razão Social</td>

<td width="32%"><input name="razao" type="text" id="razao" size="50" /></td>

<td width="11%">Nome Fantasia: </td>

<td width="37%"><input name="nome_fantasia" type="text" id="nome_fantasia" size="50" /></td>

</tr>

<tr>

<td>CNPJ</td>

<td><input name="cnpj" type="text" maxlength="18" />

ex:(xx.xxx.xxx/000x-xx)</td>

<td>CPF:</td>

<td><input name="cpf" type="text" id="cpf" size="20" maxlength="12" />

ex:(Não coloque pontos ou traços)</td>

</tr>

<tr>

<td>I.E.</td>

<td colspan="3"><input type="text" name="ie" /></td>

</tr>

<tr>

<td>Nomes para Contatos:</td>

<td colspan="3"><input name="contato1" type="text" id="contato1" /> <input name="contato2" type="text" id="contato2" /> <input name="contato3" type="text" id="contato3" /></td>

</tr>

<tr>

<td>Endereço:</td>

<td colspan="3"><input name="endereco" type="text" size="50" /></td>

</tr>

<tr>

<td>Complemento:</td>

<td colspan="3"><input type="text" name="complemento" /></td>

</tr>

<tr>

<td>CEP:</td>

<td colspan="3"><input type="text" name="cep" /></td>

</tr>

<tr>

<td>Bairro:</td>

<td colspan="3"><input name="bairro" type="text" size="30" /></td>

</tr>

<tr>

<td>Cidade:</td>

<td colspan="3"><input name="cidade" type="text" size="30" /></td>

</tr>

<tr>

<td>Estado:</td>

<td colspan="3">

<select name="est"><option value="" selected>Escolher

<option value="ACRE">AC

<option value="ALAGOAS">AL

<option value="AMAZONAS">AM

<option value="AMAPÁ">AP

<option value="BAHIA">BA

<option value="CEARÁ">CE

<option value="DISTRITO FEDERAL">DF

<option value="ESPÍRITO SANTO">ES

<option value="GOIÁS">GO

<option value="MARANHÃO">MA

<option value="MATO GROSSO">MT

<option value="MATO GROSSO DO SUL">MS

<option value="MINAS GERAIS">MG

<option value="PARANÁ">PR

<option value="PARAÍBA">PB

<option value="PARÁ">PA

<option value="PERNAMBUCO">PE

<option value="PIAUÍ">PI

<option value="RIO DE JANEIRO">RJ

<option value="RIO GRANDE DO NORTE">RN

<option value="RIO GRANDE DO SUL">RS

<option value="RONDÔNIA">RO

<option value="RORAIMA">RR

<option value="SANTA CATARINA">SC

<option value="SERGIPE">SE

<option value="SAO PAULO">SP

<option value="TOCANTINS">TO

</select></td>

<td width="1%"></select></tr>

<tr>

<td>País:</td>

<td colspan="3"><select name="pais" id="pais">

<option value="Brasil" selected="selected">Brasil</option>

</select></td>

</tr>

<tr>

<td>Email:</td>

<td colspan="3"><input name="email" type="text" id="email" size="50" /></td>

</tr>

<tr>

<td>Email 2:</td>

<td colspan="3"><input name="email2" type="text" id="email2" size="50" /></td>

</tr>

<tr>

<td>Telefone</td>

<td colspan="3"><input name="ddd" type="text" id="ddd" size="4" maxlength="3" />

<input name="telefone" type="text" id="telefone" size="20" maxlength="8" />

Ramal:

<input name="ramal" type="text" id="ramal" size="10" maxlength="5" /></td>

</tr>

<tr>

<td>Telefone 2</td>

<td colspan="3"><input name="ddd_2" type="text" id="ddd_2" size="4" maxlength="3" />

<input name="telefone2" type="text" id="telefone2" size="20" maxlength="8" />

Ramal:

<input name="ramal2" type="text" id="ramal2" size="10" maxlength="5" /></td>

</tr>

<tr>

<td>Celular</td>

<td colspan="3"><input name="ddd_cel" type="text" id="ddd_cel" size="4" maxlength="3" />

<input name="celular" type="text" id="celular" size="20" maxlength="8" /></td>

</tr>

<tr>

<td>Fax</td>

<td colspan="3"><input name="ddd_fax" type="text" id="ddd_fax" size="4" maxlength="3" />

<input name="fax" type="text" id="fax" size="20" maxlength="8" /></td>

</tr>

<tr>

<td>Website</td>

<td colspan="3"><input name="site" type="text" id="site" size="30" /></td>

</tr>

<tr>

<td><input name="tipo" type="hidden" value="corp" /></td>

<td colspan="3"><input name="cad" type="submit" id="cad" value="Cadastrar" class="botao" /> <input name="limpa" type="reset" id="limpa" value="Limpar" class="botao"/></td>

</tr>

 

</table>

</form>

</body>

</html>

 

 

 

 

Obrigado a todos!!!

Espero uma luz e obrigado de novo

Compartilhar este post


Link para o post
Compartilhar em outros sites

Bom,

 

Você disse que já fez o código, mas pelo que notei falta chamar as funções. Vou tentar exemplificar como você deviria chamá-las:

 

1- No botão de Submit do Form iremos chamar a função verifica:

<input name="cad" type="submit" id="cad" value="Cadastrar" class="botao" onclick="verifica();" />

 

2- Vamos fazer umas alterações na função verifica:

PHP

[*]function verifica(){

[*] CNPJ = document.validacao.cnpj.value;

[*] CPF = document.validacao.CPF.value;

[*] if(CNPJ=="" && CPF==""){

[*] alert('Digite um CPF ou um CNPJ!');

[*] event.returnValue=false;

[*] }

[*] if(CPF!=""){

[*] if(!validaCPF()){

[*]  event.returnValue=false;

[*]  alert('CPF Inválido!');

[*] }

[*] }

[*] else{

[*] if(!validaCNPJ()){

[*]  event.returnValue=false;

[*]  alert('CNPJ Inválido!');

[*] }

[*] } 

[*]}

O event.returnValue=false serve para anular a ação de Submit do Form. Caso o processamento não entre em nenhum IF é pq vai estar tudo OK então a ação Submit vai ser executada.

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.