Skip to content

Instantly share code, notes, and snippets.

@Tox86
Forked from gaulatti/validarRUT.html
Created November 22, 2018 17:09
Show Gist options
  • Save Tox86/a3a267b27618f6f48ba1ee58543f60cc to your computer and use it in GitHub Desktop.
Save Tox86/a3a267b27618f6f48ba1ee58543f60cc to your computer and use it in GitHub Desktop.
HTML5 Chilean RUT Validator
<!doctype html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Validador de RUT HTML5</title>
</head>
<body>
<form>
<input type="text" id="rut" name="rut" required oninput="checkRut(this)" placeholder="Ingrese RUT">
<button type="submit">Validar RUT y Enviar Form</button>
<script src="validarRUT.js"></script>
</form>
</body>
</html>
function checkRut(rut) {
// Despejar Puntos
var valor = rut.value.replace('.','');
// Despejar Guión
valor = valor.replace('-','');
// Aislar Cuerpo y Dígito Verificador
cuerpo = valor.slice(0,-1);
dv = valor.slice(-1).toUpperCase();
// Formatear RUN
rut.value = cuerpo + '-'+ dv
// Si no cumple con el mínimo ej. (n.nnn.nnn)
if(cuerpo.length < 7) { rut.setCustomValidity("RUT Incompleto"); return false;}
// Calcular Dígito Verificador
suma = 0;
multiplo = 2;
// Para cada dígito del Cuerpo
for(i=1;i<=cuerpo.length;i++) {
// Obtener su Producto con el Múltiplo Correspondiente
index = multiplo * valor.charAt(cuerpo.length - i);
// Sumar al Contador General
suma = suma + index;
// Consolidar Múltiplo dentro del rango [2,7]
if(multiplo < 7) { multiplo = multiplo + 1; } else { multiplo = 2; }
}
// Calcular Dígito Verificador en base al Módulo 11
dvEsperado = 11 - (suma % 11);
// Casos Especiales (0 y K)
dv = (dv == 'K')?10:dv;
dv = (dv == 0)?11:dv;
// Validar que el Cuerpo coincide con su Dígito Verificador
if(dvEsperado != dv) { rut.setCustomValidity("RUT Inválido"); return false; }
// Si todo sale bien, eliminar errores (decretar que es válido)
rut.setCustomValidity('');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment