Last active
September 17, 2015 15:50
-
-
Save MarcPer/f981a4e6b87493b2566c to your computer and use it in GitHub Desktop.
JavaScript function that validates check digits for Brazilian CPF and CNPJ numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Validates last two digits of a CPF or CNPJ | |
// Validation rules taken from http://ghiorzi.org/DVnew.htm | |
function validateCnpjCpf(value, type) { | |
var cpf = (type === "cpf"), | |
docLength = cpf ? 11 : 14, | |
chkLast; | |
if (value == null || value == "") { | |
return true; | |
} | |
if (typeof value !== "string" || value.length > docLength) { | |
return false; | |
} | |
value = value.replace(/[^\d]+/g,''); | |
while (value.length < docLength) | |
value = "0" + value; | |
chkLast = function(code) { | |
var len = code.length - 1, | |
sum = 0, | |
mult = function(index) { | |
return cpf ? 9 - (index % 10) : 9 - (index % 8); | |
}; | |
for (i = 0; i < len; i++) { | |
sum += code.charAt(len - 1 - i) * mult(i); | |
} | |
var dv = sum % 11; | |
dv = (dv == 10) ? 0 : dv; | |
return dv == code.charAt(len); | |
} | |
return chkLast(value.slice(0,docLength-1)) && chkLast(value); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment