JS: Form Validation

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

Screenshot

Copyright © David Heitmeyer