Skip to content

Instantly share code, notes, and snippets.

@antun
Created April 7, 2021 16:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antun/c9ff9b65c22bb2f6b40c36bb243d7e88 to your computer and use it in GitHub Desktop.
Save antun/c9ff9b65c22bb2f6b40c36bb243d7e88 to your computer and use it in GitHub Desktop.
Chile RUT Validation
var ruts = [
'12.678.579-8', // Valid - with extra digits
'76086428-5', // Valid
'220604497', // Valid no dash
'12531909-2', // Valid
'76.498.451-K', // Valid - with K verification number
'76086428', // Invalid missing verificationNumber
'12.678.579-7', // Invalid verificationNumber
'76.498.451-0', // Invalid verificationNumber
];
function validateRut(rawRut) {
var rut = String(rawRut);
var result = {
valid: true,
rawRut: rawRut,
parsedRut: null,
rutOnly: null,
verificationNumber: null,
message: ''
};
// Strip all non-numeric
rut = rut.replace(/[^0-9K]/g,'');
result.parsedRut = rut;
if (rut.length !== 9) {
result.valid = false;
result.message = 'RUT is not correct length; should be 8 digits';
return result;
}
var verificationNumber = rut.slice(-1);
result.verificationNumber = verificationNumber;
rut = rut.slice(0,-1);
result.rutOnly = rut;
var reversed = rut.split('').reverse().join('');
var total = 0;
var multiplier = 2;
for (var i=0; i<reversed.length; i++) {
total += multiplier * reversed[i];
multiplier++;
if (multiplier > 7) {
multiplier = 2;
}
}
var mod11 = total % 11;
var actualVerificationNumber = 11 - mod11;
if (actualVerificationNumber === 11) {
actualVerificationNumber = 0;
} else if (actualVerificationNumber === 10) {
actualVerificationNumber = 'K';
}
if (String(actualVerificationNumber) !== verificationNumber) {
result.valid = false;
result.message = 'Failed verification number check';
return result;
}
console.log('verificationNumber', verificationNumber);
console.log('rut', rut);
console.log('reversed', reversed);
console.log('total', total);
console.log('mod11', mod11);
console.log('actualVerificationNumber', actualVerificationNumber);
return result;
}
for (var r in ruts) {
var rut = ruts[r];
console.log('testing', rut);
var result = validateRut(rut);
console.log(result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment