Skip to content

Instantly share code, notes, and snippets.

@tiagobbraga
Created July 19, 2017 18:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tiagobbraga/184b7e6c03942587f872bbdd24f79e05 to your computer and use it in GitHub Desktop.
Save tiagobbraga/184b7e6c03942587f872bbdd24f79e05 to your computer and use it in GitHub Desktop.
CNPJ Validator for jquery form validator (http://www.formvalidator.net/)
$.formUtils.addValidator({
name : 'cnpj',
validatorFunction : function(value, $el, config, language, $form) {
value = value.replace(/[^\d]+/g,'');
if(value == '') return false;
if (value.length != 14)
return false;
// Elimina CNPJs invalidos conhecidos
if (value == "00000000000000" ||
value == "11111111111111" ||
value == "22222222222222" ||
value == "33333333333333" ||
value == "44444444444444" ||
value == "55555555555555" ||
value == "66666666666666" ||
value == "77777777777777" ||
value == "88888888888888" ||
value == "99999999999999")
return false;
// Valida DVs
tamanho = value.length - 2
numeros = value.substring(0,tamanho);
digitos = value.substring(tamanho);
soma = 0;
pos = tamanho - 7;
for (i = tamanho; i >= 1; i--) {
soma += numeros.charAt(tamanho - i) * pos--;
if (pos < 2)
pos = 9;
}
resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
if (resultado != digitos.charAt(0))
return false;
tamanho = tamanho + 1;
numeros = value.substring(0,tamanho);
soma = 0;
pos = tamanho - 7;
for (i = tamanho; i >= 1; i--) {
soma += numeros.charAt(tamanho - i) * pos--;
if (pos < 2)
pos = 9;
}
resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
if (resultado != digitos.charAt(1))
return false;
return true;
},
errorMessage : 'CNPJ inválido',
errorMessageKey: 'badCNPJ'
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment