Skip to content

Instantly share code, notes, and snippets.

@RikoKami
Last active January 24, 2023 17:35
Show Gist options
  • Save RikoKami/c58bd548645c3912176f9565b4d54f9a to your computer and use it in GitHub Desktop.
Save RikoKami/c58bd548645c3912176f9565b4d54f9a to your computer and use it in GitHub Desktop.
Validation of cpf and cnpj with formatting [typescript]
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