Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,8 @@ import isStrongPassword from './lib/isStrongPassword';

import isVAT from './lib/isVAT';

import isCpf from './lib/isCpf';

const version = '13.6.0';

const validator = {
Expand Down Expand Up @@ -225,6 +227,7 @@ const validator = {
isLicensePlate,
isVAT,
ibanLocales,
isCpf,
};

export default validator;
44 changes: 44 additions & 0 deletions src/lib/isCpf.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import assertString from './util/assertString';

// Brazilian CPF (Cadastro de Pessoas Físicas)

export default function isCpf(cpfString) {
assertString(cpfString);

let sum = 0;
let rest;

const cpf = cpfString.toString().replace(/[^0-9]+/g, '');

if (cpf === '00000000000') {
return false;
}

for (let i = 1; i <= 9; i++) {
sum += parseInt(cpf.substring(i - 1, i), 10) * (11 - i);
}
rest = (sum * 10) % 11;

if (rest === 10 || rest === 11) {
rest = 0;
}
if (rest !== parseInt(cpf.substring(9, 10), 10)) {
return false;
}

sum = 0;
for (let i = 1; i <= 10; i++) {
sum += parseInt(cpf.substring(i - 1, i), 10) * (12 - i);
}
rest = (sum * 10) % 11;

if (rest === 10 || rest === 11) {
rest = 0;
}

if (rest !== parseInt(cpf.substring(10, 11), 10)) {
return false;
}
return true;
}

23 changes: 23 additions & 0 deletions test/validators.js
Original file line number Diff line number Diff line change
Expand Up @@ -11070,4 +11070,27 @@ describe('Validators', () => {
],
});
});

it('should validate if has a valid brazilian cpf', () => {
test({
validator: 'isCpf',
args: ['57170743019',
'25997505049',
'465.839.300-05',
'369.440.070-29',
'918.309.182-03',
'12839471041',
'84018401229',
'1309972150',
'1570758018',
],
valid: ['57170743019', '25997505049', '465.839.300-05', '369.440.070-29'],
invalid: ['918.309.182-03',
'12839471041',
'84018401229',
'00000000000',
'1309972150',
'1570758018'],
});
});
});