tags:

views:

36

answers:

3

Hi! How can I validate a South African cell phone number? The number must start with the country code like +27 and be max 11 digits long - total 12 with the "+" sign.

+3  A: 

Try a regular expression like:

^\+27[0-9]{9}$

Translated to PHP that would be:

if( preg_match( "/^\+27[0-9]{9}$/", $phoneNumber ) ){
  echo "Valid number";
} else {
  echo "Invalid number";
}
Harmen
Please do NOT use this. Every site that validates phone numbers badly makes me leave straight away. Allow hyphens and spaces, don't force the +.
Coronatus
@Coronatus: The number must validate under these conditions: 'The number must start with the country code like +27 and be max 11 digits long - total 12 with the "+" sign'. Allowing whitespaces and hyphens will make the number longer than 12 characters.
Harmen
@Coronatus - I don't see the problem in forcing your users to type a valid phonenumber - just like a valid username or email. Controlling the users input is a fairly good practice when you wan't to protect your application.
Repox
@Harmenm @Repox - Not everybody (or every culture) writes phone numbers as one long list of numbers. Many people and cultures use hyphens, spaces, or every dots. The non-numeric characters should be removed server-side (see my answer).
Coronatus
@Coronatus: Read the question one more time, it states: `The number must start with the country code like +27 and be max 11 digits long - total 12 with the "+" sign`. Maybe this isn't even about user input.
Harmen
@Harmen - 90% chance it is about user input. It doesn't matter what the question says. If someone writes "how do I parse HTML in regex", they should be told of the downsides and why not to use regex for that. This is a similar case.
Coronatus
A: 
$number = preg_replace('/[^0-9]/', '', $number);
if ((substr($number, 0, 2) != '27') || strlen($number) != 11)
{
    return false;
}
// else valid
Coronatus
If you strip off all non-numbers first, a 'phone number' like `27abc554def23565` is valid too...
Harmen
A: 

Take the input and strip out everything which is not a number.

// rm all but Numbers
$input = '0123 abc #';
$output = preg_replace('#[^0-9]#', '', $input);
echo($output);

Count the remaining digits.

If it is 9 digits long, prepend "+27"

If it is 11 digits long prepend a "+"

If it is 10 digits long or less than 9, then presumably it is not a valid tel number format?

Cups