JS: Form Validation

Note that we use the "submit" event on the "form" itself.
(NOT the "click" event on the <input type="submit"/>!)

Validate form input using the onsubmit event attribute.

Things to note:

Example 8.8 - Simple Form Validation - Example 8.8

 <form onsubmit="return Validate(this)" method="get" action="https://cscis12.dce.harvard.edu/echo">
   <div>
     <label for="YourName1">Enter your name     </label>:
     <input type="text" id="YourName1" name="YourName"/>

     <br/>

     <input type="submit" value="Submit Information"/>

   </div>
 </form>

In script element within head element (<script>):

function Validate(myForm) {
  console.log(myForm);
  if(myForm.YourName.value == null || myForm.YourName.value == "") {
    console.log("in failure branch");
    alert("Please enter your name!");
    myForm.YourName.focus();
    myForm.YourName.style.backgroundColor = '#ff3';
    return false;
  } else {
    console.log("in success branch");
    return true;
  }
}
 

Screenshot