1

I wanted to add the - char after typing 5 characters like this:

enter image description here

but I got this:

enter image description here

My code :

interface IAddress {
  bairro: string;
  cep: string;
  cidade: string;
  complemento: string;
  rua: string;
  numero: string;
}
export default function App() {
  const [address, setAddress] = useState<IAddress>({
    bairro: "",
    cep: "",
    cidade: "",
    complemento: "",
    rua: "",
    numero: ""
  });
  const handlerCep = (e: any) => {
    const { value } = e.target;
    const cep = value.replace(/[^0-9]/g, "");
    setAddress({
      ...address,
      cep: address.cep.length === 5 ? `${cep}-` : cep
    });
  };
  return (
    <div className="App">
      <input
        type="tel"
        maxLength={9}
        value={address.cep}
        onChange={(e) => handlerCep(e)}
        //  onBlur={(ev) => findCep(ev)}
        required
        id="cep"
      />
    </div>
  );
}

I'm freaking out at some point and I can't imagine how I can solve this live example here :

Code sandbox: https://codesandbox.io/s/silly-sea-o4gd5?file=/src/App.tsx

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Ming
  • 1,349
  • 4
  • 13
  • 36
  • Probably you can use something like that: https://www.npmjs.com/package/react-input-mask to resolve your problem. –  Jan 17 '21 at 21:15
  • Does this answer your question? [Javascript Input Text Masking without Plugin](https://stackoverflow.com/questions/40513950/javascript-input-text-masking-without-plugin) – jmargolisvt Jan 17 '21 at 21:42
  • I'm having difficulties, could you help me? I delete the key, but whenever I type the 6 I type it replaces the string – Ming Jan 17 '21 at 21:47

1 Answers1

0

There are few problems in your code, first your regexp clears the "-" symbol on line:

// update regexp to allow '-'
const cep = value.replace(/[^0-9\-]/g, "")

second - you are checking length of property in state, instead of cep const variable. State is not yet updated, so you should be interested in checking the length of value from onchange event and update the state with calculated value

setAddress({
      ...address,
      // use cep in length check instead of address.cep
      cep: cep.length === 5 ? `${cep}-` : cep
    });

After fixing issues above - your should see input is updated as expected. Third issue to think about - case with deletion of characters, I suppose it wont work smoothly with current code.

udalmik
  • 7,838
  • 26
  • 40
  • hi, can u helpme with regex to no replace "-" ? – Ming Jan 17 '21 at 22:04
  • like I found a problem with that, I can use 9 "-" could i split into groups? something with group with 5 numbers 1 - and 3 numbers? – Ming Jan 17 '21 at 22:36