Last active
March 31, 2022 18:30
-
-
Save pedrosancao/321e4f0de31fd9cc0d52600b8335382e to your computer and use it in GitHub Desktop.
cleanest CPF/CNPJ validation
This file contains hidden or 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
const validaCNPJ=c=>((p,rd,f,u)=>p.length===14&&p[rd]((a, v)=>a===u?v:(a===v?a:f))===f&&[12,13][rd]((a,l)=>(r=>a&&(r<2?0:11-r)===p[l])(p.slice(0,l).reverse()[rd]((a,n,i)=>a+n*((i%8)+2),0)%11),!f))(c.replace(/\D/g,'').split('').map(n=>parseInt(n)),'reduce',false) |
This file contains hidden or 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
function validaCNPJ(cnpjString) { | |
let cnpj = cnpjString.replace(/\D/g, ''); | |
if (cnpj.length !== 14) { | |
return false; | |
} | |
let pieces = cnpj.split('').map(n => parseInt(n)); | |
// valida digitos iguais | |
if (pieces.reduce((a, v) => a === undefined ? v : (a === v ? a : false)) !== false) { | |
return false; | |
} | |
// valida digitos verificadores | |
return [12, 13].reduce((a, len) => { | |
let remain = pieces.slice(0, len).reverse().reduce((a, n, i) => a + n * ((i % 8) + 2), 0) % 11; | |
return a && (remain < 2 ? 0 : 11 - remain) === pieces[len]; | |
}, true); | |
} |
This file contains hidden or 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
const validaCPF=c=>((p,rd,f,u)=>p.length===11&&p[rd]((a, v)=>a===u?v:(a===v?a:f))===f&&[9,10][rd]((a,l)=>(r=>a&&(r<2?0:11-r)===p[l])(p.slice(0,l).reverse()[rd]((a,n,i)=>a+n*(i+2),0)%11),!f))(c.replace(/\D/g,'').split('').map(n=>parseInt(n)),'reduce',false) |
This file contains hidden or 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
function validaCPF(cpfString) { | |
let cpf = cpfString.replace(/\D/g, ''); | |
if (cpf.length !== 11) { | |
return false; | |
} | |
let pieces = cpf.split('').map(n => parseInt(n)); | |
// valida digitos iguais | |
if (pieces.reduce((a, v) => a === undefined ? v : (a === v ? a : false)) !== false) { | |
return false; | |
} | |
// valida digitos verificadores | |
return [9, 10].reduce((a, len) => { | |
let remain = pieces.slice(0, len).reverse().reduce((a, n, i) => a + n * (i + 2), 0) % 11; | |
return a && (remain < 2 ? 0 : 11 - remain) === pieces[len]; | |
}, true); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment