Question

I've created a contact form on my website, and wish to validate that the telephone number is made up entirely of numbers only, including a leading zero if one is entered.

I've got the following code in my sendmail.php file:

if ( empty($_REQUEST['phone']) ) {
    $pass = 1;
    $alert .= $emptyphone;
} elseif (preg_match('/^[0-9]+$/', $_REQUEST['phone'] ) ) { 
    $pass = 1;
    $alert .= $alertphone;

This code should check the field phone to see if it is made up entirely of numbers.

If not, it then calls the message $alertphone to tell the user there's a problem.

Was it helpful?

Solution 2

elseif (!preg_match('/^[0-9]+$/', $_REQUEST['phone'] ) ) { should do the job. As the RegEx you use stands for the correct phone number, you need to issue the warning if there is no match found, not in case there is a match found.

OTHER TIPS

Validating a phone number isn't quite as simple as has so far been suggested. Not only do you have to check that the phone number only contains numbers you also have to make sure that it is the correct length. You also need to make sure that you don't make it difficult for the end user to... use... otherwise you'll end up losing customers.

Example:

If I enter my phone number as 09999 999 999 it won't validate with your system. Because it contains spaces a lot of people do enter phone numbers this way and other, more complex, ways.

Code

if(empty($_REQUEST['phone'])){
    //Empty phone number
}
else if(preg_match('/^(0\d{10}|[1-9]\d{9})$/', $_REQUEST['phone'], $matches)){
    //Good phone number
}
else{
    //Bad phone number
}

Regex Explained

  1. ^ - Start of string
  2. ( - Start a capture group
  3. 0\d{10} - Match a 0 followed by an additional 10 numbers
  4. | - ...OR...
  5. [1-9]\d{9} - Match a non-0 number followed by 9 other numbers
  6. ) - Close capture group
  7. $ - Match end of string

Additional Checks

People often add spaces or brackets/punctuation to make a phone number easier to read/remember for a human. Some examples of phone number input might be:

  • (00000) 999 999
  • (0)9999 999 999
  • 09999 999 999
  • 09999999999
  • 9999999999

These would all be valid phone numbers but wouldn't be accepted by your system...

To fix this (and make life for users much easier) you would remove characters from the phone number that aren't numbers and then check it for length.

$phoneNumber = "(09999) 999 999";
$phoneNumber = preg_replace('/[^\d]/', '', $phoneNumber); //Replace non-numbers with nothing
echo $phoneNumber; //Outputs: 09999999999

A Note On Security

I strongly suggest that yo do not use $_REQUEST and instead use $_POST or $_GET as an extra security step. Explicitly using the method that you're expecting the data to come through is one more validation step to make sure that the request is legitimate.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top