Excellent code for Mask and Validation of CNPJ, CPF, CEP Data and Telephone

formulario campos obrigatorios filtros
form mandatory fields filters

(OBS 02/17/2014 - Another very good code for validation: Creating masks on forms with Jquery)

Looking for a code for CNPJ Mask and Validation I found an excellent code that allows me to create other masks (RG Mask for example).

I found the code on the website Imasters Forum.

Below is the code of the form:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<title>Formatacao de campos</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
&lt;script language="JavaScript" type="text/javascript" src="MascaraValidacao.js"></script> 
<form name="form1" action="">
<input type="text" name="cep" onkeypress="MascaraCep(form1.cep);"
 maxlength="10" onblur="ValidaCep(form1.cep)">
<input type="text" name="data" onkeypress="MascaraData(form1.data);"
 maxlength="10" onblur= "ValidaDataform1.data);">
<input type="text" name="tel" onkeypress="MascaraTelefone(form1.tel);" 
maxlength="14"  onblur="ValidaTelefone(form1.tel);">
<input type="text" name="cpf" onblur="ValidarCPF(form1.cpf);" 
onkeypress="MascaraCPF(form1.cpf);" maxlength="14">
<input type="text" name="cnpj" onkeypress="MascaraCNPJ(form1.cnpj);" 
maxlength="18" onblur="ValidarCNPJ(form1.cnpj);">
<input type="hidden" name="trp-form-language" value="en_us"/></form>

Follow the JavaScript MascaraValidacao.js

// JavaScript Document
//adiciona mascara de cnpj
function MascaraCNPJ(cnpj){
                event.returnValue = false;
        return formataCampo(cnpj, '00.000.000/0000-00', event);

//adiciona mascara de cep
function MascaraCep(cep){
                event.returnValue = false;
        return formataCampo(cep, '00.000-000', event);

//adiciona mascara de data
function MascaraData(data){
                event.returnValue = false;
        return formataCampo(data, '00/00/0000', event);

//adiciona mascara ao telefone
function MascaraTelefone(tel){  
                event.returnValue = false;
        return formataCampo(tel, '(00) 0000-0000', event);

//adiciona mascara ao CPF
function MascaraCPF(cpf){
                event.returnValue = false;
        return formataCampo(cpf, '000.000.000-00', event);

//valida telefone
function ValidaTelefone(tel){
        exp = /\(\d{2}\)\ \d{4}\-\d{4}/
                alert('Numero de Telefone Invalido!');

//valida CEP
function ValidaCep(cep){
        exp = /\d{2}\.\d{3}\-\d{3}/
                alert('Numero de Cep Invalido!');               

//valida data
function ValidaData(data){
        exp = /\d{2}\/\d{2}\/\d{4}/
                alert('Data Invalida!');                        

//valida o CPF digitado
function ValidarCPF(Objcpf){
        var cpf = Objcpf.value;
        exp = /\.|\-/g
        cpf = cpf.toString().replace( exp, "" ); 
        var digitoDigitado = eval(cpf.charAt(9)+cpf.charAt(10));
        var soma1=0, soma2=0;
        var vlr =11;

        soma1 = (((soma1*10)%11)==10 ? 0:((soma1*10)%11));

        var digitoGerado=(soma1*10)+soma2;
                alert('CPF Invalido!');         

//valida numero inteiro com mascara
function mascaraInteiro(){
        if (event.keyCode < 48 || event.keyCode > 57){
                event.returnValue = false;
                return false;
        return true;

//valida o CNPJ digitado
function ValidarCNPJ(ObjCnpj){
        var cnpj = ObjCnpj.value;
        var valida = new Array(6,5,4,3,2,9,8,7,6,5,4,3,2);
        var dig1= new Number;
        var dig2= new Number;

        exp = /\.|\-|\//g
        cnpj = cnpj.toString().replace( exp, "" ); 
        var digito = new Number(eval(cnpj.charAt(12)+cnpj.charAt(13)));

        for(i = 0; i<valida.length; i++){
                dig1 += (i>0? (cnpj.charAt(i-1)*valida[i]):0);  
                dig2 += cnpj.charAt(i)*valida[i];       
        dig1 = (((dig1%11)<2)? 0:(11-(dig1%11)));
        dig2 = (((dig2%11)<2)? 0:(11-(dig2%11)));

        if(((dig1*10)+dig2) != digito)  
                alert('CNPJ Invalido!');


//formata de forma generica os campos
function formataCampo(campo, Mascara, evento) { 
        var boleanoMascara; 

        var Digitato = evento.keyCode;
        exp = /\-|\.|\/|\(|\)| /g
        campoSoNumeros = campo.value.toString().replace( exp, "" ); 

        var posicaoCampo = 0;    
        var NovoValorCampo="";
        var TamanhoMascara = campoSoNumeros.length;; 

        if (Digitato != 8) { // backspace 
                for(i=0; i<= TamanhoMascara; i++) { 
                        boleanoMascara  = ((Mascara.charAt(i) == "-") || (Mascara.charAt(i) == ".")
                                                                || (Mascara.charAt(i) == "/")) 
                        boleanoMascara  = boleanoMascara || ((Mascara.charAt(i) == "(") 
                                                                || (Mascara.charAt(i) == ")") || (Mascara.charAt(i) == " ")) 
                        if (boleanoMascara) { 
                                NovoValorCampo += Mascara.charAt(i); 
                        }else { 
                                NovoValorCampo += campoSoNumeros.charAt(posicaoCampo); 
                campo.value = NovoValorCampo;
                  return true; 
        }else { 
                return true; 

Also, in this code, I inserted a Mask for RG, very easy:

//adiciona mascara ao RG
function MascaraRG(rg){
                event.returnValue = false;
        return formataCampo(rg, '00.000.000-0', event);

The form is as follows:

<label for="rg">RG*</label><br />
<input name="rg" type="text" id="rg" size="30" maxlength="12" onkeypress="MascaraRG(form1.rg);" />

 6,129 Total Visualizações,  8 Visualizações Hoje


  1. Good morning Fabio. A short time ago, I got the CPF validator code to test and received many complaints that the CPF was right. I decided to validate it and it looks like your algorithm really isn't 100%. I am sending this message only so that you can correct it and not (harm) any programmer. For you to be sure, I am sending you 2 valid cpfs that your algorithm is showing as invalid: 10116988380 and 10119995290 I hope I helped. Please confirm receipt of this message

  2. Hi Fabio
    Congratulations on the function, but the CPF has a problem. I have a CPF that I cannot post in public here but that is valid in the recipe and the function here was said as invalid I gave an alert on digitoGerado! = DigitoDigitado and she gave 40! = 30

  3. Cool I really liked the file
    but for being half or totally lay
    I have a question

    how do I in the case to incorporate it to the WHMCS?

  4. Good afternoon Brother, your code is very good, the best I have seen so far. However he says that my CPF is invalid, just my rsrsrsrsrsrsrsrsrs, but it works perfectly.

  5. Guys, it's working fine, but you'll have to validate it with characters.

    CPF: 000.000.000-00
    CNPJ: 00.000.000 / 0000-00

    1. Hi.

      I don't know if you have already tested it, but the masks work only on the PC. If you test on a cell phone or smartphone the masks don't work ... do you know what it can be? I'm being beaten up by this.

  6. Fabio

    Less is more ..., congratulations on the code, if it were possible I would like guidance on how to format a mask and validate the field for uppercase characters with your code.

    Again congratulations, very good!

  7. Hey guys.

    I don't know if anyone has tested it, but the masks work only on the PC. If you test on a cell phone or smartphone the masks don't work ... does anyone know what it might be? I'm being beaten up by this.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.