UNPKG

documentid-checksum-validator

Version:
52 lines (46 loc) 2.31 kB
// Function to validate the CPF in BR 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports['default'] = isValidDocId; function isValidDocId(value) { var textFieldValue = value; // Function to validate the CPF in BR var valueArray = textFieldValue.split(''); if (valueArray.length < 11 || valueArray.length > 11 || value === '11111111111' || value === '22222222222' || value === '33333333333' || value === '44444444444' || value === '55555555555' || value === '66666666666' || value === '77777777777' || value === '88888888888' || value === '99999999999' || value === '00000000000') { return false; } var CPF_SIZE = 10; var sum = [0, 0]; var isTenthDigitZero = false; var isEleventhDigitZero = false; /* below loop is to store result of the below two equation Consider the CPF written as 11 digits as c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] dv[1] dv[2], then equation I : c[1]*10 + c[2]*9 + c[3]*8 + c[4]*7 + c[5]*6 + c[6]*5 + c[7]*4 + c[8]*3 + c[9]*2 + dv[1] equation II : c[2]*10 + c[3]*9 + c[4]*8 + c[5]*7 + c[6]*6 + c[7]*5 + c[8]*4 + c[9]*3 + dv[1]*2 + dv[2] */ for (var i = 0; i < 2; i++) { var m = 10; // Multiplier which is initially set to 10 CPF_SIZE += i; // Incremented bcoz we have to include last digit for the equation 2 var x = undefined; // below loop is to multiply the each digits (As per equation 1 and 2) with the multiplier for (var j = i; j < CPF_SIZE; j++) { x = valueArray[j]; sum[i] = sum[i] + x * m--; if (i === 0 && j === 9) { isTenthDigitZero = x === 0; } else if (i === 1 && j === 10) { isEleventhDigitZero = x === 0; } } } // get the modulus of 11 with the result from equation 1 and 2 var mod1 = sum[0] % 11; var mod2 = sum[1] % 11; // return CPF validation as true only when Modulus 11 of equation I and II is 0 or // if Modulus of 11 is 1 and 10th digit is 0(in case of equation I) and 11th digit (in case of equation II) is 0 return (mod1 === 0 || mod1 === 1 && isTenthDigitZero) && (mod2 === 0 || mod2 === 1 && isEleventhDigitZero); } module.exports = exports['default'];