Last active
August 24, 2017 22:04
-
-
Save MarcAstr0/e329e7120fdc64251ccc774d47e26e6e to your computer and use it in GitHub Desktop.
JavaScript function to check whether a string is a valid Chilean ID number, also known as RUT (Rol Único Tributario) or RUN (Rol Único Nacional)
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) { | |
var cleanRut = rut.replace(/[\.|-]/g, ''); | |
var dv = cleanRut.substr(-1); | |
var rest = cleanRut.substr(0, cleanRut.length-1); | |
var digits = rest.split('').reverse().map(function(d, i) { return [(i%6)+2, parseInt(d)]; }); | |
var sum = digits.map(function(x) { return x[0]*x[1]; }).reduce(function(x, y) { return x+y; }); | |
var result = 11 - (sum % 11); | |
switch(result) { | |
case 11: | |
return (0 === dv); | |
case 10: | |
return ('K' == dv.toUpperCase()); | |
default: | |
return (result == dv); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment