title: Validating Phone Numbers Using Javascript
body: <p>I'm working on a web form with several fields and a submit button. When the button is clicked, I have to verify that the required text boxes have been filled in and that the phone number is in the correct format. I can only accept 7 or 10 digit phone numbers, but characters such as (,), (-), etc are acceptable. If this box is empty or the phone number isn't in the correct format (not 7 or 10 numbers long, not a number) or has been left blank, I have to add a red border around the text box. This border is supposed to remain in place until the user corrects the error. </p>
  
  <p>I can't get this to work properly. I have tried several different ways to go about doing this, but have gotten several different types of errors. One way seemed to work, but the red border only displayed for a second and then disappeared and the value in the textbox was reset. </p>
  
  <p>Here is my code and a link to a jsfiddle I've created:</p>
  
  <p>Javascript:</p>
  
  <pre><code>&lt;script type="text/javascript"&gt;
      function validateForm() {
          return checkPhone();
      }
      function checkPhone() {
          var phone = document.forms["myForm"]["phone"].value;
          var phoneNum = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/; 
              if(phone.value.match(phoneNum)) {
                  return true;
              }
              else {
                  document.getElementById("phone").className = document.getElementById("phone").className + " error";
                  return false;
              }
          }
  &lt;/script&gt;
  </code></pre>
  
  <p>HTML:</p>
  
  <pre><code>&lt;form name="myForm" onsubmit = "return validateForm()"&gt;
      Phone Number: &lt;input type="text" id="phone"&gt;&lt;br&gt;
  &lt;/form&gt;
  </code></pre>
  
  <p>JSFiddle:</p>
  
  <p><a href="http://jsfiddle.net/mkdsjc0p/" rel="nofollow noreferrer">http://jsfiddle.net/mkdsjc0p/</a></p>