jueves, 28 de febrero de 2019

Validador de DPI / CUI en C#

Este método valida un número de CUI / DPI de Guatemala.

Se basa en la implementación Java del siguiente blog http://xcodegt.blogspot.com/2016/09/funcion-para-validar-cui-guatemala-con.html

Se actualizó el dato del número de municipios por departamento, ya que ha variado desde 2016 (fecha del post original) a la fecha.

1:  private static bool ValidarDPI(string dpi)  
2:  {  
3:     var regex = "^[0-9]{4}-[0-9]{5}-[0-9]{4}$";  
4:     var test = Regex.IsMatch(dpi, regex);  
5:    
6:     if (!test)  
7:     {  
8:        return false;  
9:     }  
10:    
11:     var cui = dpi.Replace("-", "");  
12:    
13:     var numero = cui.Substring(0, 8);  
14:
15:
16:     var depto = Convert.ToInt32(cui.Substring(9, 2));  
17:     var muni = Convert.ToInt32(cui.Substring(11, 2));  
18:    
19:     var validador = Convert.ToInt32(cui.Substring(8, 1));  
20:    
21:     // Conteo de municipios por departamento  
22:     int[] munisPorDepto =   
23:     {  
24:        /* 01 - Guatemala    */ 17,  
25:        /* 02 - El Progreso   */ 8,  
26:        /* 03 - Sacatepéquez  */ 16,  
27:        /* 04 - Chimaltenango  */ 16,  
28:        /* 05 - Escuintla    */ 14,  
29:        /* 06 - Santa Rosa   */ 14,  
30:        /* 07 - Sololá     */ 19,  
31:        /* 08 - Totonicapán   */ 8,  
32:        /* 09 - Quetzaltenango */ 24,  
33:        /* 10 - Suchitepéquez  */ 21,  
34:        /* 11 - Retalhuleu   */ 9,  
35:        /* 12 - San Marcos   */ 30,  
36:        /* 13 - Huehuetenango  */ 33,  
37:        /* 14 - Quiché     */ 21,  
38:        /* 15 - Baja Verapaz  */ 8,  
39:        /* 16 - Alta Verapaz  */ 17,  
40:        /* 17 - Petén      */ 14,  
41:        /* 18 - Izabal     */ 5,  
42:        /* 19 - Zacapa     */ 11,  
43:        /* 20 - Chiquimula   */ 11,  
44:        /* 21 - Jalapa     */ 7,  
45:        /* 22 - Jutiapa     */ 17  
46:     };  
47:    
48:     if (muni == 0 || depto == 0)  
49:     {  
50:        return false;  
51:     }  
52:    
53:     if (depto > munisPorDepto.Length)  
54:     {  
55:        return false;  
56:     }  
57:    
58:     if (muni > munisPorDepto[depto - 1])  
59:     {  
60:        return false;  
61:     }  
62:    
63:     int total = 0;  
64:     for (int i = 0; i < numero.Length; i++)  
65:     {  
66:        total += (Convert.ToInt32(numero.Substring(i, 1))) * (i + 2);  
67:     }  
68:    
69:     int modulo = total % 11;  
70:    
71:     return modulo == validador;  
72:  }  

No hay comentarios:

Publicar un comentario