title: Using different variables with the same javascript function
body: <p>I am trying to create a generic Javascript function that I can use to verify different field values and output the error message alongside the correct field. I would like to create an efficient, reusable function, but I am new to Javascript and am unsure how to proceed.</p>
  
  <p>Advise on how to change my validation function to validate both <code>firstname</code> and <code>lastname</code> would be appreciated.</p>
  
  <p>My code so far:</p>
  
  <pre><code>function validateForm() {
      var x = document.forms["myForm"]["firstname"].value;
      var reg_azs = /^[^a-zA-Z\-']+$/;
      var reg_oal = "!#$%^&amp;*()+=[]\\\';,{}|\":&lt;&gt;?123456790";
  
      if (x == null || x == "") {
          document.getElementById("fn").innerHTML = "This fuild is required.";
          return false;
      } else if (reg_azs.test(firstname.value)) {
          document.getElementById("fn").innerHTML = "Only alphabetic letters.";
          return false;
      } else {
          for (var i = 0; i &lt; x.length; i++) {
              if (reg_oal.indexOf(x.charAt(i)) != -1) {
                  document.getElementById("fn").innerHTML = "Only alphabetic letters.";
                  return false;
              }
          }
      } else {
          document.getElementById("fn").innerHTML = "correct";
          return true;
      }
  }
  </code></pre>
  
  <p>My Form:</p>
  
  <pre><code>&lt;form name="myForm" action="connection.php" method="post"&gt;
      &lt;label for='firstname'&gt;First Name:&lt;/label&gt;
      &lt;input type="text" id="firstname" name="firstname" onchange="return validateForm()" /&gt;
      &lt;err1 id="fn"&gt;&lt;/err1&gt;
      &lt;br&gt;  
  
      &lt;label for='lastname'&gt;Last Name:&lt;/label&gt;
      &lt;input type="text" id="lastname" name="lastname" onchange="return validateForm()" /&gt;
      &lt;err1 id="ln"&gt;&lt;/err1&gt;
      &lt;br&gt;
  &lt;/form&gt;
  </code></pre>