Javascript Regular Expression for Phone with IDD

Asked

Viewed 14,684 times

4

I’m having trouble understanding the logic of Regex, and I can’t find codes that make up the complete phone mask with IDD, DDD and phone with 8 and 9 digits with change of hyphen when typing directly in the field using for example the onkeyup event.

Follow mask +99 (99) 9999-9999 or +99 (99) 99999-9999

4 answers

13

You can use the following expression:

/^(?:\+)[0-9]{2}\s?(?:\()[0-9]{2}(?:\))\s?[0-9]{4,5}(?:-)[0-9]{4}$/

Hard to understand? It was generated through the tool Simple Regex Language:

begin with literally "+",
digit exactly 2 times,
whitespace optional,
literally "(", digit exactly 2 times, literally ")",
whitespace optional,
digit between 4 and 5 times,
literally "-",
digit exactly 4 times,
must end

I believe that in this way it becomes self-explanatory.

See working here.

  • 2

    +1 by Simple Regex Language. Sensational

  • @Arthurmenezes, yes, she has saved me many times.

  • I just hope they’re not saying that \s be it whitespace of " "

  • 1

    @Guilhermelautert, any spacing, as is standard of regex. See documentation ("This Matches any whitespace Character. This includes a space, tab or new line.")

3

The below regex valid the mask you need

JS

var RegExp = /\+\d{2}\s\(\d{2}\)\s\d{4,5}-?\d{4}/g;
var t = "+99 (99) 99999-9999";
RegExp.test(t); //true

var t2 = "+99 (99) 9999-9999";
RegExp.test(t2); //true

var t3 = "+99 (99) 999999-9999";
RegExp.test(t3); //false

3

You can do it this way:

var regExp = /^\+?\d{2}?\s*\(\d{2}\)?\s*\d{4,5}\-?\d{4}$/g;
var telefone = '+55 (55) 23321-5454';
var resultado = regExp.test(telefone); //retorna true ou false

0

Function for Phone Mask with IDD

function mTel(tel) {
    tel=tel.replace(/\D/g,"")
    tel=tel.replace(/^(\d)/,"+$1")
    tel=tel.replace(/(.{3})(\d)/,"$1($2")
    tel=tel.replace(/(.{6})(\d)/,"$1)$2")
    if(tel.length == 12) {
        tel=tel.replace(/(.{1})$/,"-$1")
    } else if (tel.length == 13) {
        tel=tel.replace(/(.{2})$/,"-$1")
    } else if (tel.length == 14) {
        tel=tel.replace(/(.{3})$/,"-$1")
    } else if (tel.length == 15) {
        tel=tel.replace(/(.{4})$/,"-$1")
    } else if (tel.length > 15) {
        tel=tel.replace(/(.{4})$/,"-$1")
    }
    return tel;
}

Browser other questions tagged

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