5.8 The DOM 2 Event Model

<!DOCTYPE html>;
<!-- validator2.html
     A document for validator2.js
     Note: This document works with IE9, but not earlier 
           versions of IE
     -->;
<html lang = "en">;
  <head>;
    <title>; Illustrate form input validation with DOM 2>; </title>;
    <meta charset = "utf-8" />;
    <script type = "text/javascript"  src = "validator2.js" >;
    </script>;
  </head>;
  <body>;
    <h3>; Customer Information </h3>;
    <form action = "">;
      <p>;
        <label>;
          <input type = "text"  id = "custName" />;
           Name (last name, first name, middle initial)
        </label>;
        <br />;<br />;

        <label>;
          <input type = "text"  id = "phone" />;
          Phone number (ddd-ddd-dddd)
        </label>;
        <br />;<br />;

        <input type = "reset" />;
        <input type = "submit"  id = "submitButton" />;
      </p>;
    </form>;
    <script type = "text/javascript"  src = "validator2r.js" >;
    </script>;

  </body>;
</html>;

// validator2r.js // The last part of validator2. Registers the // event handlers // Note: This script does not work with IE8 // Get the DOM addresses of the elements and register // the event handlers var customerNode = document.getElementById("custName"); var phoneNode = document.getElementById("phone"); customerNode.addEventListener("change", chkName, false); phoneNode.addEventListener("change", chkPhone, false);
// validator2.js
//   An example of input validation using the change and submit 
//   events, using the DOM 2 event model
//   Note: This document does not work with IE8

// ********************************************************** //
// The event handler function for the name text box

function chkName(event) {

// Get the target node of the event

  var myName = event.currentTarget;

// Test the format of the input name 
//  Allow the spaces after the commas to be optional
//  Allow the period after the initial to be optional

  var pos = myName.value.search(/^[A-Z][a-z]+, ?[A-Z][a-z]+, ?[A-Z]\.?$/);

  if (pos != 0) {
    alert("The name you entered (" + myName.value + 
          ") is not in the correct form. \n" +
          "The correct form is: " +
          "last-name, first-name, middle-initial \n" +
          "Please go back and fix your name");
   } 
}

// ********************************************************** //
// The event handler function for the phone number text box

function chkPhone(event) {

// Get the target node of the event

  var myPhone = event.currentTarget;

// Test the format of the input phone number
 
  var pos = myPhone.value.search(/^\d{3}-\d{3}-\d{4}$/);
 
  if (pos != 0) {
    alert("The phone number you entered (" + myPhone.value +
          ") is not in the correct form. \n" +
          "The correct form is: ddd-ddd-dddd \n" +
          "Please go back and fix your phone number");
  } 
}