6

How do I validate a UK phone number in C# using a regex?

travis
  • 35,751
  • 21
  • 71
  • 94
LeoD
  • 2,002
  • 5
  • 25
  • 24

1 Answers1

30

The regex in the accepted answer does not match all valid UK numbers, as it is too restricive (additional number ranges have been opened up in the meanwhile such as 0203, which it sees as invalid).

UK phone numbers follow fairly simple rules:

  • They can be either 10 or 11 digits long (with the exception of some special numbers, but you're unlikely to need to validate those)

  • They consist of an area code followed by a local number. The area code varies in length between three and five digits, and the local portion of the number takes up the remaining length of the 10 or 11 digits. For all practical purposes, no-one ever quotes just the local portion of their number, so you can ignore the distinction now, except for how it affects formatting.

  • They start with zero.

  • The second digit can be anything. Currently no valid numbers start with 04 or 06, but there's nothing stopping these ranges coming into use in the future. (03 has recently been brought into use)

  • They can be formatted with a set of brackets and with spaces (one or more, in varying positions), but those are all entirely optional.

Therefore, a basic working expression for UK phone numbers could look like this:

/^\(?0( *\d\)?){9,10}$/

This will check for 10 or 11 digit numbers, starting with a zero, with formatting spaces between any of the digits, and optionally a set of brackets for the area code.

(and yes, this would allow mis-matched brackets, as I'm not checking that there's only one closing bracket. Enforcing this would make the expression a lot more complex, and I don't have time for this right now, but feel free to add this if you wish)

By the way, in case you want to do additional filtering, you might want to also note the following rules:

  • Numbers starting 08, 09 and 070 are special price numbers, and would not generally be given as private numbers, so can be excluded if validating a private number.

  • 07 numbers are mobile (except 070; see above) so can be excluded if you're specifically validating for a landline.

Spudley
  • 166,037
  • 39
  • 233
  • 307
  • 1
    I'ld like to add a comment (especially now in 2016) that auto-fill from address books etc will populate phone numbers with the international dialing code of 44 or +44 replacing the leading 0. My regex-foo isn't strong enough to modify your regex to fix for that though. – Jmons May 02 '17 at 08:30
  • The National Significant Number (NSN) can be 10, 9 or 7 digits (giving a full number length of 11, 10 or 8 digits) https://en.wikipedia.org/wiki/Telephone_numbers_in_the_United_Kingdom#Format – Andy Preston Sep 21 '20 at 10:38