-1
  1. The minimum number of characters (excluding spaces) is 11 and the maximum is 13.
  2. If the user is entering a phone number starting with something other than '07' or '+447', then the minimum characters is 10 and the maximum is 13.
  3. User can enter space.

Following numbers should pass regex

  • 07424689253 (11)
  • +447424689253 (13)
  • 02049533525 (11)
  • 0169773355 (10)

I have write this regex but not working. Please help

/^(\(?(0|\+44)[1-9]{1}\d{1,4}?\)?\s?\d{3,4}\s?\d{3,4})$/
Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
Ban_meg
  • 31
  • 6

1 Answers1

0

Try this

/^\s*(?:\+44(?:\s*\(\s*0\s*\))?|0)\s*(7(?:\s*\d){9}|(?=\d)[^7](?:\s*\d){8,9})\s*$/
//    ^-------------A------------^    ^-----B-----^ ^-----------C----------^
  • A is international/domestic code, i.e. +44, 0 or +44 (0), consider adding 0044, 0044 (0)
  • B is mobile phone number, 7 followed by 9 more digits
  • C is a landline number, non-7 followed by 8 or 9 more digits, consider breaking into region groups

Spaces are permitted throughout the whole thing except in the +44

There is a capture group which will give you the result of either B or C, depending on the match


Examples

var re = /^\s*(?:\+44(?:\s*\(\s*0\s*\))?|0)\s*(7(?:\s*\d){9}|(?=\d)[^7](?:\s*\d){8,9})\s*$/;

// Mobile
'+44 (0) 712 345 6789'.match(re); // ["+44 (0) 712 345 6789", "712 345 6789"]
'+44 712 345 6789'.match(re);     // ["+44 712 345 6789",     "712 345 6789"]
'0712 345 6789'.match(re);        // ["0712 345 6789",        "712 345 6789"]

// Landline
'020 4 953 3525'.match(re); // ["020 4 953 3525", "20 4 953 3525"]
'016 977 3355'.match(re);   // ["016 977 3355",   "16 977 3355"]

Useful RegExp patterns used here

  • (?:pattern) Non-capture group; This pattern is a group but not captured seperately
  • (?:\s*\d){9} Any amount of whitespace followed by a number, 9 times
  • (?=pattern) Lookahead; Look to see if pattern would match next, but don't match it
  • (?=\d)[^7], If the next character is a digit match the next character if it isn't a 7
Paul S.
  • 64,864
  • 9
  • 122
  • 138
  • I've never seen the `(07222) 555555` format written before today so I didn't include it, and you may need to double-check the permitted lengths of landline numbers – Paul S. Oct 27 '15 at 15:05
  • Solid answer with a thorough explanation and examples. This a very nicely written answer, good job :) – Sabrina Oct 27 '15 at 15:14