JavaScript Regular Expression for Phone with DDI

2

I'm having difficulty understanding Regex logic, and I do not think codes that make up the complete phone mask with DDI, DDD, and 8- and 9-digit phones with hyphen changes when typing right in the field using for example the onkeyup event .

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

    
asked by anonymous 10.03.2017 / 17:55

3 answers

8

You can use the following expression:

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

Difficult to understand? It was generated using the Simple Regex Language tool:

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 it's self-explanatory in this way.

See working here .

    
10.03.2017 / 18:09
2

The regex below holds 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
    
10.03.2017 / 19:00
2

You can do this as follows:

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
    
22.03.2017 / 18:02