Last active
January 24, 2023 17:35
-
-
Save RikoKami/c58bd548645c3912176f9565b4d54f9a to your computer and use it in GitHub Desktop.
Validation of cpf and cnpj with formatting [typescript]
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
const regex = { | |
cnpj: /^(\d{2})(\d{3})?(\d{3})?(\d{4})?(\d{2})?$/u, | |
cpf: /^(\d{3})(\d{3})?(\d{3})?(\d{2})?$/u, | |
}; | |
const replaceValue = { | |
cnpj: "$1.$2.$3/$4-$5", | |
cpf: "$1.$2.$3-$4", | |
}; | |
interface ResponseCpfOrCnpj { | |
field: string; | |
type: "cnpj" | "cpf"; | |
} | |
function validateCpfOrCnpj(field: string): ResponseCpfOrCnpj | never { | |
const lengthField = field.replace(/\D/gu, "").length; | |
const typeField = lengthField === 14 ? "cnpj" : "cpf"; | |
if (lengthField > 14 || lengthField < 11) { | |
throw new TypeError(`Field: '${field}' is invalid`); | |
} | |
return { | |
field: field.replace(/\D/gu, "").replace(regex[typeField], replaceValue[typeField]), | |
type: typeField, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment