Search code examples
phpregexpreg-matchphone-number

Trouble with preg_match and numbers


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.


Solution

  • 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.