1
Context: have a input that as I type a function is called to check if the phone number is in the correct format. This function must accept numbers in the formats: (XX)XXXXX-XXXX and (XX)XXXX-XXXX, and already accepts both formats!
What’s the matter then?: The function when giving match in 8 digit format does not continue the correction if the user type the 9th digit.
In short: I want regex to identify both 8 and 9 digit formats, but if 9 digits are entered, this format should be used.
import React, {useState} from 'react'
function App(){
const [telefone, setTelefone] = useState("")
function handleTelefone(event){
const regex = /^\(?([0-9]{2})\)?([0-9]{4,5})\-?([0-9]{4})$/mg;
var str = event.target.value;
const subst = `($1)$2-$3`;
const result = str.replace(regex, subst);
setTelefone(result);
}
return(
<>
<form>
<input type="text" value={telefone} onChange={handleTelefone.bind(this)}/>
</form>
</>
)
}
export default App