Skip to content

simple brazilian masks to use on day to day (CNPJ, CPF, CEP, Phone, PIS)

Notifications You must be signed in to change notification settings

gabrielnafuzi/brazilian-masks

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

23 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Brazilian Masks

Some masks commonly used in forms in Brazil

Available Masks

  • phone (dynamically changes)
  • cnpj
  • cpf
  • cpfOrCnpj (dynamically changes)
  • cep
  • pis

Utility functions

  • clear (remove all non-numeric characters)

Installation

npm i @nafuzi/brazilian-masks

or

yarn add @nafuzi/brazilian-masks

Simple use (Vanilla JS)

import { clear, cep } from '@nafuzi/brazilian-masks'

const cepInput = document.getElementById('cep-input')

cepInput.addEventListener('input', (event) => {
  const { value } = event.target

  cepInput.value = cep(value)
})

React (TypeScript)

// MaskedInput.tsx
import type { ChangeEvent, HTMLProps } from 'react'
import masks, { type MasksName } from '@nafuzi/brazilian-masks'

type MaskedInputProps = {
  mask: MasksName
  onChange: (maskedValue: string) => void
} & Omit<HTMLProps<HTMLInputElement>, 'onChange'>

export const MaskedInput = ({
  name,
  value,
  onChange,
  mask,
  ...rest
}: MaskedInputProps) => {
  const handleOnChange = (event: ChangeEvent<HTMLInputElement>) => {
    const maskedValue = masks[mask](event.target.value)

    onChange(maskedValue)
  }

  return <input onChange={handleOnChange} value={value} {...rest} />
}

// App.tsx
import { useState } from 'react'

import { MaskedInput } from './components/MaskedInput'

const App = () => {
  const [cpf, setCpf] = useState('')

  return (
    <MaskedInput
      name="cpf"
      value={cpf}
      onChange={(value) => setCpf(value)}
      mask="cpf"
    />
  )
}

export default App

Contributing

Feel free to create issues and open PR's with features, improvements, bugfix, etc.

License

MIT

About

simple brazilian masks to use on day to day (CNPJ, CPF, CEP, Phone, PIS)

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published