Skip to content

Instantly share code, notes, and snippets.

@walison17
Last active July 12, 2019 14:26
Show Gist options
  • Save walison17/47933ab235f3fb5bf087968b7ed11945 to your computer and use it in GitHub Desktop.
Save walison17/47933ab235f3fb5bf087968b7ed11945 to your computer and use it in GitHub Desktop.
function validateCns(cns) {
cns = cns.replace(/\D/g, '');
if (cns.length != 15) {
return false;
}
const primeiroDigito = cns.charAt(0);
// Validação para CNS provisório
if (['7', '8', '9'].includes(primeiroDigito)) {
let soma = [...cns]
.map((digito, index) => parseInt(digito) * (15 - index))
.reduce((acumulado, valor) => acumulado + valor);
return soma % 11 == 0;
}
// Validação para CNS definitivo
if (['1', '2'].includes(primeiroDigito)) {
const base = cns.substring(0, 11);
let soma = [...base]
.map((digito, index) => parseInt(digito) * (15 - index))
.reduce((acumulado, valor) => acumulado + valor);
let dv = 11 - (soma % 11);
if (dv == 11) {
dv = 0;
}
let resultado = '';
if (dv == 10) {
soma += 2;
dv = 11 - (soma % 11);
resultado = `${base}001${dv}`;
} else {
resultado = `${base}000${dv}`;
}
return resultado == cns;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment