Skip to content

Instantly share code, notes, and snippets.

@gmelendezcr
Forked from jrmoran/isDui.js
Created September 3, 2012 13:44
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save gmelendezcr/3609421 to your computer and use it in GitHub Desktop.
Save gmelendezcr/3609421 to your computer and use it in GitHub Desktop.
Verificacion DUI
/*
DUI = 00016297-5
Posiciones -> 9 8 7 6 5 4 3 2
DUI -> 0 0 0 1 6 2 9 7
DV = 5
sum: (9*0) + (8*0) + (7*0) + (6*1) + (5*6) + (4*2) + (3*9) + (2*7) = 85
residuo: (85 % 10) = 5
resta: 10 - residuo = 5
IF DV == Resta THEN true ELSE false
*/
var isDUI = function(str){
var regex = /(^\d{8})-(\d$)/,
parts = str.match(regex);
// verficar formato y extraer digitos junto al digito verificador
if(parts !== null){
var digits = parts[1],
dig_ve = parseInt(parts[2], 10),
sum = 0;
// sumar producto de posiciones y digitos
for(var i = 0, l = digits.length; i < l; i++){
var d = parseInt(digits[i], 10);
sum += ( 9 - i ) * d;
}
return dig_ve === (10 - ( sum % 10 ))%10;
}else{
return false;
}
};
isDUI('00016297-5'); // true
isDUI('12345678-1'); // false
isDUI('123456789-1'); // false
isDUI('12345678-12'); // false
@gmelendezcr
Copy link
Author

La verificación fallaba cuando el dígito verificador del DUI es cero.

@lu1tr0n
Copy link

lu1tr0n commented Jun 5, 2020

Perfeto!! Gracias por la ayuda.

@kevra550
Copy link

me ayudo de maravilla, muchas gracias!

@sergio9508
Copy link

gracias

@douglashb
Copy link

douglashb commented Jun 1, 2022

Muchas gracias me sirvio, dejo la función en PHP.

Funciona desde PHP >= 7.2

Online
https://onlinephp.io/c/90ffc

Script

function isDUI($dui) {
	
	if ((bool)preg_match('/(^\d{8})-(\d$)/', $dui) === true) {
            [$digits, $digit_veri] = explode('-', $dui);
            $sum = 0;

            for ($i = 0, $l = strlen($digits); $i < $l; $i++) {
                $sum += (9 - $i) * (int)$digits[$i];
            }
			
            return (int)$digit_veri === (10 - ($sum % 10)) % 10);
        }
	
	return false;
}

@javier-marroquin
Copy link

javier-marroquin commented Sep 15, 2023

Gracias, les comparto como queda en Python:

Probado en Python >= 3.9

En línea

https://pythonsandbox.dev/qc8dwrvc7kuh

Función

import re
def is_dui(dui):
    if re.match(r'^\d{8}-\d$', dui):
        digits, digit_veri = dui.split('-')
        sum = 0

        for i in range(len(digits)):
            sum += (9 - i) * int(digits[i])

        return int(digit_veri) == (10 - (sum % 10)) % 10

    return False
res = is_dui('04288874-5')
print(res)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment