-11

I have this phone regex, but I want it to accept spaces.

For example +57 52 5252255 should pass, but currently it's not passing. also "+91 9 820 09 8200" should pass so a space anywhere is acceptable

var phone_regex =/^\s*(?:\+?(\d{1,3}))?[- (]*(\d{3})[- )]*(\d{3})[- ]*(\d{4})(?: *[x/#]{1}(\d+))?\s*$/;

https://jsfiddle.net/ofn9knay/268/

James marcus
  • 55
  • 1
  • 1
  • 8
  • related: https://stackoverflow.com/questions/50978414/normalize-phone-numbers-using-python – Sheshank S. Jun 21 '18 at 23:16
  • Just a thought, am sure someone will fix the regex for you but I would try strip away all the unnecessary symbols and spaces before validating the number. This way, you could define your own format for phone numbers before inserting it into your DB. – James Wong Jun 22 '18 at 03:54

2 Answers2

0

In order to match that string, your second capturing group needs to accept 2 or 3 digits.

pattern = /^\s*(?:\+?(\d{1,3}))?[- (]*(\d{2,3})[- )]*(\d{3})[- ]*(\d{4})(?: *[x/#]{1}(\d+))?\s*$/;

test_strings = [
    "+57 52 5252255",
    "9820098200#301",
    "+919820098200",
    "+91-982-009-8200",
    "+1 (866) 582-2655",
    "+91 444 741 4000",
];

for (var i = 0; i < test_strings.length; i++) {
  console.log(test_strings[i] + ": " + pattern.test(test_strings[i]));
}
fubar
  • 16,918
  • 4
  • 37
  • 43
chuckx
  • 6,484
  • 1
  • 22
  • 23
  • i want the space to be anywhere not at certain places – James marcus Jun 22 '18 at 03:42
  • The current regular expression does accept spaces between the number sets. Do you want a regular expression that will match an indefinitely repeated set of space/dash delimited series of numbers of arbitrary length? Can only the second set be surrounded by parentheses? Most importantly, do you have additional test strings? – chuckx Jun 22 '18 at 05:02
0

We could try to tweak your existing complicated regex, but assuming you already have the phone number as an input in a variable, then one simple thing to do would be to just remove all whitespace:

var phone_regex =/^\s*(?:\+?(\d{1,3}))?[- (]*(\d{3})[- )]*(\d{3})[- ]*(\d{4})(?: *[x/#]{1}(\d+))?\s*$/;
var phone = "+91 9 820 09 8200";
phone = phone.replace(/ /g,'');
console.log(phone_regex.test(phone));

Then, just use your current regex as you were doing.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360