title: Javascript form validation highlight invalid character
body: <p>I'm just working on some really basic form validation with JS. I don't want users to be able to use any special characters on input fields as a layer of defense against XSS exploits. </p>
  
  <p>I've got the basic validation down and it seems to work ok but it just says there is an error and I would like to highlight the invalid character. here is my code.</p>
  
  <p>HTML</p>
  
  <pre><code>&lt;head&gt;&lt;meta charset="UTF-8"&gt;&lt;script src="script.js"&gt;&lt;/script&gt;&lt;/head&gt;
  &lt;body&gt;
  
  &lt;form method="post" action="test.php" onsubmit="return validate()"&gt;
      &lt;p&gt;&lt;input type="text" id="userName" placeholder="Username or Email"&gt;&lt;/p&gt;
      &lt;p&gt;&lt;input type="password" id="userEmail" placeholder="Password"&gt;&lt;/p&gt;
      &lt;p&gt;&lt;input type="submit" id="submit" value="Login"&gt;&lt;/p&gt;
  &lt;/form&gt;
  
  &lt;input type="button" value="debug" onclick="debug()"&gt;
  
  &lt;p id="errorText"&gt;&lt;/p&gt;
  &lt;p id="debug"&gt;&lt;/p&gt;
  &lt;/body&gt;
  </code></pre>
  
  <p>Javascript</p>
  
  <pre><code>&lt;script&gt;
  
      function validate() {
      var userName = document.getElementById('userName').value;
      var userEmail = document.getElementById('userEmail').value;
      var invalidChars = "!,@,#,$,%,^,&amp;,*,(,),&lt;,&gt;,/,~,`";
      var mergeFields = userName.concat(userEmail);
      var found = "false";
      var invCharsArr = invalidChars.split(",");
      var fieldsArr = mergeFields.split("");
      var nameErr = "false";
      var emailErr = "false";
  
      for (var i = 0; i &lt; fieldsArr.length; i++) {
              if (invCharsArr.indexOf(fieldsArr[i]) &gt; -1) {
              found = "true";
              break;
              }
      }
  
      if (found == "true") {
          document.getElementById('errorText').innerHTML = "You used an invalid character";
          return false;
      }
      else {
          if (userName == "" || userName == null) {
              document.getElementById('userName').style.backgroundColor = "red";
              document.getElementById('errorText').innerHTML = "Field Errors are Highlighted in Red";
              nameErr = "true";
              return false;
          }
          else if (userEmail == "" || userEmail == null) {
              document.getElementById('userEmail').style.backgroundColor = "red";
              document.getElementById('errorText').innerHTML = "Field Errors are Highlighted in Red";
              emailErr = "true";
              return false;
          }
          else {
              return true;
          }
      }
  
      }
  
  &lt;/script&gt;
  </code></pre>
  
  <p>On a side note I am still a beginner with javascript, if there is anything here that I can do better please let me know I would like to learn. Thanks</p>