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
2010-10-30 09:11:59
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
2010-10-30 09:20:01
@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
2010-10-30 09:45:50
@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
2010-10-30 09:47:24
@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
2010-10-30 09:58:42
@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
2010-10-30 10:01:31
@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
2010-10-30 10:15:17
A:
$number = preg_replace('/[^0-9]/', '', $number);
if ((substr($number, 0, 2) != '27') || strlen($number) != 11)
{
return false;
}
// else valid
Coronatus
2010-10-30 09:12:51
If you strip off all non-numbers first, a 'phone number' like `27abc554def23565` is valid too...
Harmen
2010-10-30 09:17:50
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
2010-10-30 10:28:44