-
-
Save user0able/ce3b4d892b9b694c5ad6b11a2e25f2c9 to your computer and use it in GitHub Desktop.
HTML5 Chilean RUT Validator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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