I am trying to prevent typing 0 (zero) at the beginning of phone number after the country code.
I am using:
- Next.Js
- NumberFormat (react-number-format)
The problem: I was able to prevent 0 from typing. When I run console.log(number);, it works as I want however NumberFormat doesn't take number as a value. It basically doesn't update. I have no idea how I can prevent 0 at the beginning.
On top of that allowLeadingZeros={false} doesn't work as well.
Expected result: If I start typing 0, it should remove it. For example if I am typing 06 99 99 99 99, it should show +33 6 99 99 99 99 by removing 0 at the beginning.
I don't know what am I missing. I noticed it works sometimes.
This is my code:
import React, { useState } from "react";
import NumberFormat from "react-number-format";
export default function FormContact(props, initialValues = {}) {
const [number, setNumber] = useState("");
const onValueChangeNumber = (e) => {
if (/^0/.test(e.value)) {
e.value = e.value.replace(/^0/, "");
setNumber(e.value);
}
console.log("If there is no zero, it worked", number); //This shows 0 prevented at the beginning as expected.
console.log("Formatted Change", e.value); //This shows 0 prevented at the beginning as expected.
};
const onChangeNumber = (e) => {
console.log("Normal Change", e.target.value); //This shows 0 at the beginning.
};
return (
<>
<NumberFormat
type="tel"
key="phoneNumber"
name="tel"
placeholder="Téléphone"
value={number}
onValueChange={onValueChangeNumber}
onChange={onChangeNumber}
allowLeadingZeros={false}
format="+33 # ## ## ## ##"
mask="_"
/>
</>
);
}
Thanks in advance for your suggestions.