title: Form Validation with Javascript using window.onload
body: <p>Hi there I am really stuck on this and since I am a javscript beginner this boggles my mind.</p>
  
  <p>Is there someone who knows how to write the following javascript form validation?
  I am sure that it is very simple, but I can not figure this one out to save my life.</p>
  
  <p>Thank you for you sharing your knowledge.</p>
  
  <p>I need to write WITHOUT jquery the following form validation. Whenever an error is encountered, prevent the form from being submitted. I need to use the window.onload function to assign a validation callback function. There are 4 inputs which get validated by the javascript code. Also the javascript needs to be in its own file. </p>
  
  <p>Validation Rules are as follow:</p>
  
  <p>INPUT: Username; Required (yes); Validation (Must be 5-10 characters long).
  INPUT: Email; Required (yes); Validation (Must have an @ sign, must have a period).
  INPUT: Street name; Required (no); Validation (Must start with a number).
  INPUT: Year of birth; Required (yes); Validation (must be numeric). </p>
  
  <p>My code looks as follow:</p>
  
  <hr>
  
  <p>HTML:</p>
  
  <hr>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
  &lt;head&gt;
  
  
  &lt;script defer="defer" type="text/javascript" src="form.js"&gt;&lt;/script&gt;
  
  
  &lt;/head&gt;
  &lt;body&gt;
  &lt;form action="fake.php"&gt;
      Username*: &lt;input type="text" class="required" name="u"/&gt;&lt;br/&gt;
      Email*: &lt;input type="text" class="required" name="p"/&gt;&lt;br/&gt;
      Street address: &lt;input type="text" class="numeric" name="s"/&gt;&lt;br/&gt;
      Year of birth*: &lt;input type="text" class="required numeric" name="b"/&gt;&lt;br/&gt;
  
  
      &lt;input type="submit"/&gt;&lt;br/&gt;
  &lt;/form&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <hr>
  
  <h2>JS</h2>
  
  <pre><code>document.forms[0].elements[0].focus();
  
  document.forms[0].onsubmit=function(){
  
  for(var i = 0; i &lt; document.forms[0].elements.length; i++){
  
  var el = document.forms[0].elements[i];
  
  if((el.className.indexOf("required") != -1) &amp;&amp; 
    (el.value == "")){
  
  alert("missing required field");
   el.focus();
  el.style.backgroundColor="yellow";
   return false;
  }
  
  if((el.className.indexOf("numeric") != -1) &amp;&amp; 
   (isNaN(el.value))){
  
  
  alert(el.value + " is not a number");
   el.focus();
  el.style.backgroundColor="pink";
   return false;              
    }
   }
  }
  </code></pre>