Skip to content

Instantly share code, notes, and snippets.

@vinibortoletto
Created August 13, 2024 21:02
Show Gist options
  • Select an option

  • Save vinibortoletto/497f2ca31d2155b9af0b13a7acc09f68 to your computer and use it in GitHub Desktop.

Select an option

Save vinibortoletto/497f2ca31d2155b9af0b13a7acc09f68 to your computer and use it in GitHub Desktop.
format and validade cpf
import { cpf } from 'cpf-cnpj-validator';
const TAMANHO_MAXIMO = 14;
export const formatar = (valor: string) => {
return valor
.replace(/\D/g, '')
.replace(/(\d{3})(\d)/, '$1.$2')
.replace(/(\d{3})(\d)/, '$1.$2')
.replace(/(\d{3})(\d{1,2})/, '$1-$2')
.replace(/(-\d{2})\d+?$/, '$1')
};
export const validar = (valor: string) => {
const cpfInvalido = valor.length === TAMANHO_MAXIMO && !cpf.isValid(valor);
if (cpfInvalido) return 'CPF inválido'
return '';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment