Conditional formatting of Regex phone number

Asked

Viewed 768 times

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

1 answer

2

The problem is in the approach. The regex you have even validates the sequence (XX)XXXXX-XXXX, but as you format the input when typing a sequence of 10 digits, when the user enters with the 11th digit, the input gets the format (XX)XXXX-XXXXX.

I usually format the value of the input, leaving only significant characters (numbers in this case) before making these validations, so you don’t need to worry about validation of the hyphen or parentheses, example:

function handleTelefone(event) {
  const regex = /^([0-9]{2})([0-9]{4,5})([0-9]{4})$/;
  var str = event.target.value.replace(/[^0-9]/g, "").slice(0, 11);

  const result = str.replace(regex, "($1)$2-$3");

  setTelefone(result);
}

See the result working here

Browser other questions tagged

You are not signed in. Login or sign up in order to post.