Last active
May 17, 2022 19:19
-
-
Save lgaticaq/2e5de70146e34afe0968eed49bc533ad to your computer and use it in GitHub Desktop.
Función para validar DNI Peruano
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
/** | |
* Verifica que un DNI de Perú sea valido | |
* @param {String} data DNI | |
* @returns {Boolean} | |
*/ | |
const validate = data => { | |
const dni = data.replace('-', '').trim().toUpperCase() | |
if (!dni || dni.length < 9) return false | |
const multiples = [3, 2, 7, 6, 5, 4, 3, 2] | |
const dcontrols = { | |
numbers: [6, 7, 8, 9, 0, 1, 1, 2, 3, 4, 5], | |
letters: ['K', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'] | |
} | |
const numdni = dni.substring(0, dni.length - 1).split('') | |
const dcontrol = dni.substring(dni.length - 1) | |
const dsum = numdni.reduce((acc, digit, index) => { | |
acc += digit * multiples[index] | |
return acc | |
}, 0) | |
const key = 11 - (dsum % 11) | |
const index = (key === 11) ? 0 : key | |
if (/^\d+$/.test(dni)) { | |
return dcontrols.numbers[index] === parseInt(dcontrol, 10) | |
} | |
return dcontrols.letters[index] === dcontrol | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
El algoritmo es válido. Seguro es un error en tu código. He copiado, pegado y buscado el dni que has escrito.
{"dni":"71390300","nombres":"CARLOS FRANCO","apellidoPaterno":"TAIPE","apellidoMaterno":"SALVATIERRA","codVerifica":"6"}
El resultado de la operación es 11. Lo que significa que es el índice 0.
const index = (key === 11) ? 0 : key
Saludos