title: jQuery validation of NANP Phone numbers
body: <p>I'm trying to validate my form. In my form is a phone number field. The user inserts a phone number and validation takes place as well as formatting. I've read a lot of the other similar questions in StackOverflow and through searches elsewhere, but I'm stuck. The form keeps saying that a valid number I insert is invalid.</p>
  
  <p>I'm only concerned with NANP numbers and I understand the NANP numbers are formatted like this: NXX-NXX-XXXX, where N can only be digits <code>[2-9]</code>, and X can be <code>[0-9]</code>. I don't need a country code.</p>
  
  <p>Here's my code:</p>
  
  <pre><code>function validatePhone(){
      var error = 1;
  
      var hasError = false;
      var $this = $(this);
      var regex1 = /^(\()?[2-9]{1}\d{2}(\))?(-|\s)?[2-9]{1}\d{2}(-|\s)\d{4}$/;
  
      phone = $(this).val();
      phone = phone.replace(/[^0-9]/g,'');        
      if(!regex1.test(phone)){
          hasError = true;
          $this.css('background-color','#FFEDEF');
      }   
      else{
          area = phone.substring(0,3);
          prefix = phone.substring(3,6);
          line = phone.substring(6);
          $this.val('(' + area + ') ' + prefix + '-' + line);
          $this.css('background-color','#FFFFFF');    
      }
  </code></pre>
  
  <p>The idea is that no matter whether I insert 8012559553, (801)2559553, (801)255-9553, 801-255-9553 or something similar that it would be validated and formatted like this: (801) 255-9553. But again, the form for some reason continues to say that any number I insert is invalid, regardless of whether it's valid or not. This is code that I was using that was working, but didn't comply with NANP formats:</p>
  
  <pre><code>function validatePhone(){
      var error = 1;
  
      var hasError = false;
      var $this = $(this);
      phone = $(this).val();
      phone = phone.replace(/[^0-9]/g,'');        
      if(phone.length != 10){
              hasError = true;
              $this.css('background-color','#FFEDEF');
      }   
      else{
              area = phone.substring(0,3);
              prefix = phone.substring(3,6);
              line = phone.substring(6);
              $this.val('(' + area + ') ' + prefix + '-' + line);
              $this.css('background-color','#FFFFFF');    
      }
  </code></pre>
  
  <p>So, I'm having trouble implementing the regex test of the numbers to make sure that the numbers are real and then have the number formatted correctly... Any ideas?</p>