title: Phone Number Validation PHP
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation">A comprehensive regex for phone number validation</a><br>
    <a href="https://stackoverflow.com/questions/11705507/php-validation-of-us-phone-numbers">PHP: Validation of US Phone numbers</a>  </p>
  </blockquote>
  
  
  
  <p>I'm trying to validate a phone number using preg_match, but any time I type in the correct format of phone number (111) 111-1111, it returns the invalid character error instead of true. I don't think there's anything wrong with my regex (as far as I know), so I'm guessing there's something wrong with my logic</p>
  
  <pre><code>function validate_phone_number($phoneNumber, $requiredLength = 14)
  {
  
         //Check to make sure the phone number format is valid 
      for ($i = 0; $i &lt; strlen($_POST[$phoneNumber]); $i++){
              if(preg_match('/^\(\d{3}\) \d{3}-\d{4}\$/', $_POST[phoneNumber]{$i}))
              {
                  return true;
              }
              else
              {
                  return "&lt;h3&gt;" . "The phone number you entered contains invalid characters" . "&lt;/h3&gt;";
              }
  
         //Check to make sure the number is the required length
              if (strlen($_POST[$phoneNumber]) &gt; $requiredLength) {
                  return "&lt;h3&gt;" . "The phone number you entered contains too many characters" . "&lt;/h3&gt;";
              }
              else if (strlen($_POST[$phoneNumber]) &lt; $requiredLength) {
                  return "&lt;h3&gt;" . "The phone number you entered does not contain enough characters" . "&lt;/h3&gt;";
              }
          }
          return true;
  }
  </code></pre>
  
  <p>What I'm using to call the function </p>
  
  <pre><code>if (count($_POST) &gt; 0) {
      $error = array();
  
  
     $phone = validate_phone_number('phoneNumber');
          if($phone !==true) {
              $error[] = $phone;
  
          }
  
  
          if (count($error) == 0) {
  
             //Phone number validates
  
          }
  
          else { 
            echo "&lt;h2&gt;Error Message:&lt;/h2&gt;";
  
            foreach($error as $msg) {
              echo "&lt;p&gt;" . $msg . "&lt;/p&gt;";
            }
          }
        }
  </code></pre>