Scotto
Usuario (Nicaragua)
Dios bendiga a cada uno Validar/Verificar Número de Cédula Nicaragüense en C# Para iniciar debemos saber que el número de cédula tiene el siguiente formato: ###-######-####L un ejemplo válido sería: 281-130387-0009W. Ahora bien, los primeros tres dígitos indican el Lugar de Nacimiento (Municipio); los siguientes seis dígitos, Fecha de Nacimiento... Según nuestro ejemplo ésta persona nació el 13 de marzo de 1987 en el municipio de León El siguiente código se ejecuta mientras el usuario escribe el número de cédula en la caja de texto: private void CedulaIdentidad_KeyPress(object sender, KeyPressEventArgs e) { // Cédula de Identidad if (this.mnuCedulaIdentidad.Checked) {//281-130387-0009W // Posición de cursor en el TextBox Int32 Cursor_Pos = 0; // Longitud Máxima de caracteres this.txtID_1.MaxLength = 16; // Si Es DELETE o BACKSPACE if ((e.KeyChar == Convert.ToChar(Keys.Delete)) || (e.KeyChar == Convert.ToChar(Keys.Back))) { // Almacenar la posición del cursor Cursor_Pos = this.txtID_1.SelectionStart; // El sistema manipula la acción de la tecla e.Handled = false; } // Si no es Letra o Dígito, eliminarlo else if (!Char.IsLetterOrDigit(e.KeyChar)) e.Handled = true; // Valores permitidos else { // Si el cursor está al final del texto if (this.txtID_1.Text.Length == this.txtID_1.SelectionStart) { // Ingreso únicamente de valores numéricos if ((this.txtID_1.Text.Length >= 0) && (this.txtID_1.Text.Length < 15)) { // Si es Número if (Char.IsDigit(e.KeyChar) && !this.ContieneLetra(this.txtID_1.Text)) { // Si el largo es 3 ó 10 if ((this.txtID_1.Text.Length == 3) || (this.txtID_1.Text.Length == 10)) // Agregar - this.txtID_1.Text += "-"; // Agregar el número presionado this.txtID_1.Text += e.KeyChar.ToString(); } } // Ingresar el último caracter de la cédula else if (this.txtID_1.Text.Length == 15) { // Si es Letra if (Char.IsLetter(e.KeyChar)) // Agregar la letra presionada this.txtID_1.Text += e.KeyChar.ToString().ToUpper(); } // Administrar el caracter e.Handled = true; // Ubicar el cursor al final del texto this.txtID_1.SelectionStart = this.txtID_1.Text.Length; } // El cursor en cualquier posición diferente al final else { // Ingresar única Letra if (!this.ContieneLetra(this.txtID_1.Text)) { // ¿Es Letra? if (Char.IsLetter(e.KeyChar)) { // Agregar la letra presionada this.txtID_1.Text += e.KeyChar.ToString().ToUpper(); // Ubicar el cursor al final del texto this.txtID_1.SelectionStart = this.txtID_1.Text.Length + 1; } // ¿Es Número? else { // Ingreso únicamente de valores numéricos if ((this.txtID_1.Text.Length >= 0) && (this.txtID_1.Text.Length < 15)) { // El texto contenido en el control String value = this.txtID_1.Text; // Posición del cursor en el control Int32 inicio = this.txtID_1.SelectionStart; // Concatenar el texto this.txtID_1.Text = value.Substring(0, inicio) + e.KeyChar.ToString() + value.Substring(inicio, value.Length - inicio); // Mover el cursor una posición a la derecha this.txtID_1.SelectionStart = inicio + 1; } } // Indicar al sistema que el caracter ha sido manipulado por el usuario e.Handled = true; } // Ya tiene letra else { // ¿Es Número? if (Char.IsDigit(e.KeyChar)) { // Ingreso únicamente de valores numéricos if ((this.txtID_1.Text.Length >= 0) && (this.txtID_1.Text.Length <= 15)) { String value = this.txtID_1.Text; Int32 inicio = this.txtID_1.SelectionStart; this.txtID_1.Text = value.Substring(0, inicio) + e.KeyChar.ToString() + value.Substring(inicio, value.Length - inicio); // Mover el cursor una posición a la derecha this.txtID_1.SelectionStart = inicio + 1; } } e.Handled = true; } } Cursor_Pos = this.txtID_1.SelectionStart; } this.txtID_1.Text = this.CedulaFormato(this.txtID_1.Text); this.txtID_1.SelectionStart = Cursor_Pos; } } Como pueden observar he dado formato especial donde he llamado otro método, a continuación les muestro el código: private String CedulaFormato(String cadena) { String cedula = String.Empty; if (!cadena.IsEmpty()) { // Eliminar todos los guiones que contenga la cadena cadena = cadena.Replace("-", String.Empty); Char[] value = cadena.ToCharArray(); for (Int32 i = 0; i < cadena.Length; i++) { if ((i == 3) || (i == 9)) cedula += "-"; cedula += value; } } return cedula; } Como pueden observar he dado formato especial donde he llamado otro método... es un Método Extensión de la Clase String a continuación les muestro el código: /// <summary> /// Indica si el valor del objeto <paramref name="String"/> actual es <paramref name="null"/> /// o una cadena <paramref name="String.Empty"/> eliminando espacios en blanco /// </summary> /// <param name="value">Cadena a Evaluar</param> /// <returns><paramref name="true"/>: La cadena está vacía, en caso contrario <paramref name="false"/></returns> public static Boolean IsEmpty(this String value) { Boolean resultado = String.IsNullOrEmpty(value); if (value != null) resultado = resultado && String.IsNullOrEmpty(value.Trim()); return resultado; } Para usar éste tipo de Métodos debemos crear un namespace y dentro de éste, una clase static donde declararemos todos nuestros extensions y luego incluir using nuestro namespace en cada archivo de código. Además, esta otro método que busca si existe el único caracter alfabético en el número de cédula: private Boolean ContieneLetra(String cadena) { // Si la cadena es nula: FALSE if (cadena.IsEmpty()) return false; // Convertir de String a Char[] Char[] str = cadena.ToCharArray(); // Recorrer el Array en busca de un caracter alfabético foreach (Char c in str) { // Si el caracter es una letra: TRUE if (Char.IsLetter(c)) return true; } return false; } Una vez que hemos dado formato a la información introducida por el usuario, validemos y mostremos la información si es correcta private void CedulaIdentidad_Leave(object sender, EventArgs e) { // Cédula de Identidad if (this.mnuCedulaIdentidad.Checked) { // Longitud de la cédula if ((this.txtID_1.Text.Length != 16) && !this.txtID_1.Text.IsEmpty()) { Classes.CUtils.ShowError(this, "Error: Número de Cédula Erróneo"; this.txtID_1.Focus(); this.txtID_1.SelectAll(); return; } // Verificar si los datos son correctos else if (!this.txtID_1.Text.IsEmpty()) { Objetos.O_Municipio municipio_nac = Datos.D_Municipio.GetMunicipio(Convert.ToUInt32(this.txtID_1.Text.Substring(0, 3))); if (municipio_nac == null) { Classes.CUtils.ShowError(this, "Error: Número de Municipio Erróneo en el Número de Cédula"; // Enfocar el Control this.txtID_1.Focus(); // Seleccionar la información errónea this.txtID_1.Select(0, 3); // Salir del Evento return; } // Fecha de Nacimiento String fecha_cedula = this.txtID_1.Text.Substring(4, 6); // Información Cultural para Nicaragua System.Globalization.CultureInfo cultura = new System.Globalization.CultureInfo("es-NI"; // Fecha de Nacimiento Completa DateTime dt; // Verificar si la fecha es correcta if (!DateTime.TryParseExact(fecha_cedula, "ddMMyy", cultura, System.Globalization.DateTimeStyles.None, out dt)) { // Mensaje de Error Classes.CUtils.ShowError(this, "Error: Fecha de Nacimiento en Número de Cédula No Válido"; // Enfocar el Control this.txtID_1.Focus(); // Seleccionar la información errónea this.txtID_1.Select(4, 6); // Salir del Evento return; } else { this.txtLugarNac.Text = municipio_nac.ToString(); this.dtmrFechaNacimiento.Checked = true; this.dtmrFechaNacimiento.Value = dt; this.txtEdad.Text = Classes.CUtils.Edad(dt).ToString(); } } } } Para finalizar dejo unos enlaces con las clases: O_Municipio https://doc-0g-7s-docs.googleusercontent.com/docs/securesc/2a4h55c8gvqmdj0coehdofp4f1p3efgk/lu5m8ru8fgkfm8e6g0cr3fdd4sb3oapo/1343592000000/00761303368618812080/00761303368618812080/0B_Sqfp2_H4tIakRKWHNrdnFsems?e=download D_Municipio https://doc-08-7s-docs.googleusercontent.com/docs/securesc/2a4h55c8gvqmdj0coehdofp4f1p3efgk/7unemtuarp4sph3a7vuflhe7mbdanf65/1343592000000/00761303368618812080/00761303368618812080/0B_Sqfp2_H4tIYXkyRXpVS2xNUG8?e=download y un archivo SQL con la información de los municipios de Nicaragua Municipios https://doc-0c-7s-docs.googleusercontent.com/docs/securesc/2a4h55c8gvqmdj0coehdofp4f1p3efgk/ov1cukoj1nrb9ociq41rmvtshkdblqiv/1343592000000/00761303368618812080/00761303368618812080/0B_Sqfp2_H4tIZkJ4ajcwbHF5QnM?e=download