Skip to content

Instantly share code, notes, and snippets.

@donpandix
Last active January 7, 2024 22:29
Show Gist options
  • Save donpandix/045f865c3bf800893036 to your computer and use it in GitHub Desktop.
Save donpandix/045f865c3bf800893036 to your computer and use it in GitHub Desktop.
Valida rut Chileno con c#, basado el algoritmo modulo 11
/// <summary>
/// Validador de RUT Chileno
/// Hace uso del algoritmo Modulo 11
///
/// Chilean ID Number validator
/// Use the algorithm called Module 11
/// </summary>
class Rut {
/// <summary>
/// Metodo de validación de rut con digito verificador
/// dentro de la cadena
/// </summary>
/// <param name="rut">string</param>
/// <returns>booleano</returns>
public static bool ValidaRut(string rut) {
rut = rut.Replace(".", "").ToUpper();
Regex expresion = new Regex("^([0-9]+-[0-9K])$");
string dv = rut.Substring(rut.Length - 1, 1);
if (!expresion.IsMatch(rut)) {
return false;
}
char[] charCorte = { '-' };
string[] rutTemp = rut.Split(charCorte);
if (dv != Digito(int.Parse(rutTemp[0]))) {
return false;
}
return true;
}
/// <summary>
/// Método que valida el rut con el digito verificador
/// por separado
/// </summary>
/// <param name="rut">integer</param>
/// <param name="dv">char</param>
/// <returns>booleano</returns>
public static bool ValidaRut(string rut, string dv) {
return ValidaRut(rut + "-" + dv);
}
/// <summary>
/// método que calcula el digito verificador a partir
/// de la mantisa del rut
/// </summary>
/// <param name="rut"></param>
/// <returns></returns>
public static string Digito(int rut) {
int suma = 0;
int multiplicador = 1;
while (rut != 0) {
multiplicador++;
if (multiplicador == 8)
multiplicador = 2;
suma += (rut % 10) * multiplicador;
rut = rut / 10;
}
suma = 11 - (suma % 11);
if (suma == 11) {
return "0";
} else if (suma == 10) {
return "K";
} else {
return suma.ToString();
}
}
}
@Dizkm8
Copy link

Dizkm8 commented Nov 3, 2023

Hola! Estoy trabajando en un proyecto .NET 7 y me encontré con tu gists, te agradezco el trabajo ya que me ahorró tiempo. He cambiado unas cosas para poder adaptarlo a las nuevas versiones, por si a alguien más le llega a servir: https://gist.github.com/Dizkm8/68d63edb3c5941e45597cfaebaca03f8

Saludos!

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