Last active
July 12, 2019 14:26
-
-
Save walison17/47933ab235f3fb5bf087968b7ed11945 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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