0

I am trying to get my code to work for a form. I want it to validate a phone number. It want to continue to tell me the phone number is not correct even when it is.

Here's what I have. I took out the rest of the code that pertain to this part to simplify it. I am not sure if I have the code right but I am looking to have someone only be able to type number. Enter a 10 digit string of number and have it change to the following format (XXX) XXX-XXXX if this is possible.

<?php

include_once "contact-config.php";

$error_message = '';

if (!isset($_POST['submit'])) {

  showForm();

} else { //form submitted

  $error = 0;


 if(!empty($_POST['phone'])) {
$phone[2] = clean_var($_POST['phone']);
if (!validPhone($phone[2])) {
  $error = 1;
  $phone[3] = 'color:#FF0000;';
  $phone[4] = '<strong><span style="color:#FF0000;">Invalid Phone Number</span></strong>';
  }
 }
  else {
    $error = 1;
    $phone[3] = 'color:#FF0000;';
  } 

<td class="quote_text" style="width:{$left_col_width}; text-align:right; vertical-align:top; padding:{$cell_padding}; {$phone[3]}"><span class='required'><b>* </b></span>{$phone[0]}</td>
<td style="text-align:left; vertical-align:top; padding:{$cell_padding};"><input type="text" name="{$phone[1]}" value="{$phone[2]}" size="20" maxlength="11" id="{$phone[1]}" /> {$phone[4]}</td>


/* Phone Number Validation Function. */

function validPhone($phone)
{
  $isValid = true;
  if(array_key_exists('phone', $_POST))
  {
    if(!preg_match('/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/', $_POST['phone']))
    {
      $isValid = false;
    }
 }
 return $isValid;
 }
?>
Ni Ck
  • 91
  • 1
  • 2
  • 7

1 Answers1

0

I have a few comments about your original code although I have not gone into the debugging in depth.

  1. There's a regex at http://php.net/manual/en/function.preg-match.php that is more complicated you might try. It's about halfway down the page. I tried your regex out at both http://regexpal.com/ and http://www.solmetra.com/scripts/regex/index.php ; it did not work at either place on phone numbers I used. The regex I pulled from the PHP reference page, as shown below, works.

    /^(?:1(?:[. -])?)?(?:((?=\d{3})))?([2-9]\d{2})(?:(?<=(\d{3})))? ?(?:(?<=\d{3})[.-])?([2-9]\d{2})[. -]?(\d{4})(?: (?i:ext).? ?(\d{1,5}))?$/

  2. You're calling the function with a parameter then not using the parameter in the function body, which strikes me as strange.

  3. This is probably a duplicate topic of PHP: Validation of US Phone numbers which is pretty comprehensive.

Community
  • 1
  • 1
Dylan Brams
  • 2,089
  • 1
  • 19
  • 36