UNPKG

@sjsilva-libs/cpd-input

Version:

Componente para input e validação de CPF

57 lines (50 loc) 1.67 kB
import React, { useState } from "react"; import ReactDOM from "react-dom/client"; import { isCPF } from "@sjsilva-libs/validation"; // CPF component const CpfInput = (props) => { const { id, name, label, value, error, onChange } = props const [cpf, setCpf ] = useState(value ?? ''); const [errorMsg, setErrorMsg] = useState(null); const handleChange = (e) => { setCpf(e.target.value); onChange(cpf) } const handleBlur = () => { if (!cpf) return const numbers = cpf.replace(/\D/g, ""); const fmt = numbers.match(/.{1,3}/g).join(".").replace(/\.(?=[^.]*$)/, "-") setCpf(fmt) const isValid = isCPF(fmt) onChange({ cpf: fmt, isValid }) setErrorMsg(isValid ? null : error ?? 'CPF Inválido'); } return ( <> <fieldset> <legend>{ label }</legend> <input id={id} name={name} maxLength={11} value={cpf} onChange={handleChange} type="text" onBlur={handleBlur} /> <div style={{color: 'red', fontSize: '.7rem'}}>{ errorMsg }</div> </fieldset> </> ) } const mount = (element, { id, name, label, value, onChange }) => { ReactDOM.createRoot(element).render(<CpfInput id={id} name={name} label={label} value={value} onChange={onChange} />) } if (process.env.NODE_ENV !== "production") { const root = document.querySelector('#root') mount(root, { id: 'txtInput', name: 'txtInput', label: 'CPF', value: '', onChange: (cpf) => { console.log('CPF => ', cpf) } }) } export { mount }