Skip to content

Instantly share code, notes, and snippets.

@moshmage
Last active November 9, 2017 18:31
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save moshmage/a2949f95f20f2ebeace8fef72ec462d2 to your computer and use it in GitHub Desktop.
Chillean RUT validation
/**
* Provide string of type 12.333.333-k|123456789|12345678-9|12.345678-9
* ???
* profit.
* @param {string} _rut
* @returns {boolean}
*/
function isValidRUT(_rut) {
const isRegexValid = _rut.match(/^\d{1,2}\.?\d{3}\.?\d{3}\-?[0-9kK]$/ig);
if (!isRegexValid) return false;
/** return early if the provided string is not worthy */
const rut = _rut.replace(/\D/ig, '');
/** replace everything that's not a digit from the pool */
const rest = 11 - ([3, 2, 7, 6, 5, 4, 3, 2]
.reduce((_total, multiplier, index) => _total + (multiplier * +rut[index]), 0) % 11);
/** subtract eleven to the sum of the magic multiplication and the module of elven */
const lastChar = _rut[_rut.length - 1];
if (rest < 11 && ('' + rest) === lastChar) return true;
/** if the rest is less than elven and equal to the provided strings last character */
return rest === 11 && lastChar === '0' || rest === 10 && lastChar.search(/[kK]/ig) > -1;
/** Otherwise check if rest is eleven, or ten, and equal to 0 or K respectively */
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment