## 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:

- `onsubmit` attribute to set handler for "submit" event
- `false` stops the form submission
- `this` refers to the instance of the object (the form)
- Validate function accepts an argument, which is the form object
- On failure, focus is put on failed input and background color changed.

Example 8.8 - Simple Form Validation - Example 8.8<form onsubmit="return Validate(this)" method="get" action="https://cscis12.dce.harvard.edu/echo" enctype="application/x-www-form-urlencoded"><div><label for="YourName1">Enter your name</label>: <input type="text" id="YourName1" name="YourName"/><br/><input type="submit" value="Submit Information"/></div></form>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; } }

- Markup
- Script
- Screenshot

     <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;
      }
    }