Harvard Extension School, Fall 2018
CSCI E-12 Fundamentals of Web Site Development

## JS: Form Validation

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="http://cscie12.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="http://cscie12.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 type="text/javascript">`):

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

Copyright © David Heitmeyer