2

I am want a Regular Expression that mark as correct number for below examples:

    +256897845    
    +1 232321
    +29 2343 2432 43
    +555 2356897845
    +1245 2356878
    +918989784578
  • Must include + Symbol on start
  • Optional Support up to 3 space Like: +29 2343 2432 43
  • Minimum 8 Char including + symbol
  • Max Char 18 digit (3 Space + 4 digit max country code + Plus (+) Symbol + 10 digit max number)

i have tried my self as below but not working:

^\+[0-9]?()[0-9](\s|\S)(\d[0-9]{18})$
Shiv Singh
  • 6,939
  • 3
  • 40
  • 50

2 Answers2

2

You may use

/^\+(?=(?:\s?\d){7,17}$)\d+(?:\s?\d+){0,3}$/

See the regex demo

Details

  • ^ - start of string
  • \+ - a plus symbol
  • (?=(?:\s?\d){7,17}$) - up to the end of the string, there must appear 7 to 17 occurrences of an optional whitespace and a digit
  • \d+ - 1+ digits
  • (?:\s?\d+){0,3} - 0 to 3 occurrences of an optional whitespace and a digit
  • $ - end of string.

JS demo:

var strs = ['+256897845','+1 232321','+29 2343 2432 43','+555 2356897845','+1245 2356878','+918989784578'];
var rx = /^\+(?=(?:\s?\d){7,17}$)\d+(?:\s?\d+){0,3}$/;
for (var s of strs) {
  console.log(s, "=>", rx.test(s));
}
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

Although Wiktor's regex perfectly does the job, but I personally prefer to keep the regex simple as it will be more maintainable in case regex requirement changes which often happens.

You can write a function like this, this will not only take care of multiple spaces present anywhere but also hyphen (and other special characters) as that is also commonly present in mobile numbers and finally you can simply apply this regex /^[+]\d{7,13}$/

Demo here,

     function isValidMobileNumber(number) {
     if (number == null || number.trim().length == 0) {
      return false;
     }
     number = number.replace(new RegExp('[ -]', 'g'), '');
     var rx = /^[+]\d{7,13}$/;
     return rx.test(number);
    }
    
    var strs = ['+1-234-242-2434','+1-23-2','+123','+256897845','+1 232321','+29 2343 2432 43','+555 2356897845','+1245 2356878','+918989784578'];
    for (var s of strs) {
     console.log (s + " --> " + isValidMobileNumber(s));
    }
Pushpesh Kumar Rajwanshi
  • 18,127
  • 2
  • 19
  • 36