Last active
August 22, 2019 20:05
-
-
Save wesdeveloper/6294b9f6db87de997538b3b6a3598ed7 to your computer and use it in GitHub Desktop.
Validate if a CPF is valid
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
/** | |
* Validate if a CPF is valid. | |
* @param {String} data - CPF | |
* @param {Array} cpfBlackList - Array with balcklist of wrongs CPFs | |
* @returns {Boolean} return an boolean. | |
* | |
* @example | |
* isCpfValid('07102325364'); // false | |
*/ | |
export const isCpfValid = ( | |
data = '', | |
cpfBlackList = [ | |
'00000000000', | |
'11111111111', | |
'22222222222', | |
'33333333333', | |
'44444444444', | |
'55555555555', | |
'66666666666', | |
'77777777777', | |
'88888888888', | |
'99999999999', | |
], | |
) => { | |
const isDigitValid = (digit = 1) => { | |
const index = digit === 1 ? 9 : 10; | |
let amount = 0; | |
for (let i = 0; i < index; i++) amount += parseInt(cpf.charAt(i)) * (index + 1 - i); | |
const rest = 11 - (amount % 11); | |
if (!(rest === 10 || rest === 11) && rest !== parseInt(cpf.charAt(index))) return false; | |
return true; | |
}; | |
const cpf = data.replace(/[^\d]+/g, ''); | |
if (!cpf || cpf.length !== 11 || cpfBlackList.find(current => cpf === current)) return false; | |
return isDigitValid(1) && isDigitValid(2); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment