Example 10: Client side verification example using smart alert boxes

Best Practice Rating: Good

Example Start

Sample Form

Example was developed from DHSAccessibility Tests

Example End

HTML Source Code


  <div>
    <h2>Sample Form</h2>
    <form id="SampleForm" action="#" method="post">
      <div class="text">
        
        <label for="fname">
          First Name
          <span class="required">(Required)</span>
        </label>
        
        <input type="text"
                    name="fname"
                    id="fname"
                     size="12"
                     onblur="checkFirst(event)"/>
      </div>
      
      <div class="text">
        <label for="lname">
          Last Name
          <span class="required">(Required)</span>
        </label>
        <input type="text"
                    name="lname"
                    id="lname"
                    size="20"
                    onblur="checkLast(event)"/>
      </div>

      <div class="text">
        <label for="date">Birth Date:</label>
        <input type="text"
                    name="date"
                    id="date"
                    size="12"
                    onblur="checkDate(event)"/>
      </div>
      
      <div class="text">
        <label for="ssn"><abbr title="Social Security Number">SSN</abbr></label>
        <input type="text"
                    name="ssn"
                    id="ssn"
                     size="10"
                     onblur="checkSSN(event)"/>
      </div>

      <div class="text">
        <label for="phone">
            Phone  
          <span class="required">(Required)</span>
        </label>
        <input type="text"
                    name="phone"
                    id="phone"
                    size="14"
                    onblur="checkPhone(event)"/>
      </div>
      <div class="button">
        <input type="button"
                    value="Submit Form"
                    onclick="validateForm()"/>
      </div>
    </form>

  </div>
<p><a href="http://www.dhs.state.il.us/accessibility/tests/">Example was developed from <abbr title='Illinois Department of Health and Human Services'>DHS</abbr>Accessibility Tests</a></p>

Javascript Source Code

  <script type="text/javascript">
<!--//--><![CDATA[//><!--

var first_name_error = false;
var last_name_error = false;
var phone_error = false;

function validateForm() {
      var errorMessage = "Please complete the following fields:";
      var errorElements = new Array();
      var node;
      var result;
      var node_focus = null;
      // check required fields
      
      // Check first name
      var node = document.getElementById("fname");
      if( node && node.value == "" ) {
          errorElements.push("You must enter your first name");
      
          node_focus = node;
       }

      // Check last name
      node = document.getElementById("lname");
      if( node && node.value == "" ) {
          errorElements.push("You must enter your last name");
          
          if( node_focus == null )
             node_focus = node;
       }
      
      // Check Phone
      node = document.getElementById("phone");
      if( node  && node.value == "") {

            errorElements.push("You must enter a phone number");
            
           if( node_focus == null )
               node_focus = node;
              
      }  // endif


   first_name_error = true;
   last_name_error = true;  
   phone_error = true;  

   if( errorElements.length > 0 ) {
  
        for(i=0; i < errorElements.length; i++ ) {
        
           errorMessage += "\n" + errorElements[i];
          
        }  // end for
  
        alert(errorMessage);
  
         if( node_focus )
            node_focus.focus();
            
        return false;
   } else {
        // supress submit for test; for a real form, return true
        alert("If this were a real form, you would have just submitted it.");
        return false;
   }
  

}

function checkDate(event) {

     var node = getTarget(event);
    
     if( node ) {
       var result =  validateDate( node);
       if( result != "" ) {
           showError(node, result);
      } // endif
    } // endif
    
    return stopPropagation( event);
}


function checkFirst(event) {

     var node = getTarget(event);
    
     if( node.value.length == 0 && first_name_error ) {
           showError(node, "Please enter your first name");
           first_name_error = false;
    } // endif
    
    return stopPropagation( event);
}

function checkLast(event) {

     var node = getTarget(event);
    
     if( node.value.length == 0 && last_name_error ) {
           showError(node, "Please enter your last name");
           last_name_error = false;
    } // endif
    
    return stopPropagation( event);
}


function validateDate(node) {
      
      var errorMessage = "Date needs to be in date format, \nsuch as 1/31/2001.";

      if (node.value != "") {
        // try parsing as date using JavaScript Date constructor
        var dateValue = new Date(node.value.replace(/-/g, "/"));
        if (isFinite(dateValue)) {
          // if two-digit year, guess at correct century
          if (node.value.match(/\D\d{1,2}$/) && dateValue.getFullYear() < (new Date().getFullYear() - 96)) {
            dateValue.setFullYear(dateValue.getFullYear() + 100);
          }
          // format as mm/dd/yyyy
          node.value = (dateValue.getMonth() + 1) + "/" + dateValue.getDate() + "/" + dateValue.getFullYear();
          return "";
        }
        else {
          return errorMessage;
        }
      }
      return "";
}

function checkPhone(event ) {

     var node = getTarget( event );
    
     if( node ) {
       var result =  validatePhone( node);
       if( result != "" ) {
           showError(node, result);
      } // endif
    
      if( node.value.length == 0 && phone_error ) {
           showError(node, "Please enter your phone number");
           last_phone = false;
      } // endif
      
    } // endif
    
    return stopPropagation( event);
}

function validatePhone( node ) {
      var errorMessage = "Phone needs to be a phone number with area code, \nsuch as (555) 123-4567.";
      if (node.value != "") {
        // replace all non-digit characters, then match string starting with 2-9 (US phone numbers can't start with 0 or 1) followed by 2 digits, 3 digits, 4 digits
        if (node.value.replace(/\D/g, "").match(/([2-9]\d{2})(\d{3})(\d{4})/)) {
          // use sub-matches captured above to format as (###) ###-####
          node.value = "(" + RegExp.$1 + ") " + RegExp.$2 + "-" + RegExp.$3;
          return "";
        }
        else {
          return errorMessage;
        }
      }
      return "";      
    }

function checkSSN(event) {

     var node = getTarget( event );
    
     if( node ) {
       var result =  validateSSN( node);
       if( result != "" ) {
           showError(node, result);
      } // endif
    
    } // endif

    return stopPropagation( event);

}

function validateSSN(node) {
      var errorMessage = "Social Security Number needs to be a nine-digit number, \nsuch as 123-45-6789.";
      
      if (node.value != "") {
        // replace all non-digit characters, then match 3 digits, 2 digits, 4 digits

        if (node.value.replace(/\D/g, "").match(/(\d{3})(\d{2})(\d{4})/) ) {
          // use sub-matches captured above to format as ###-##-####
          node.value = RegExp.$1 + "-" + RegExp.$2 + "-" + RegExp.$3;
          return "";
        }
        else {
          return errorMessage;
        }
      }
      return "";
    }

    function showError(node, message) {
      alert(message);
      // focus & select element with error (Mozilla, Safari & Chrome require brief delay before moving focus)
      setTimeout(function() { node.focus(); node.select(); }, 1);
    }

    function supressEnterKeySubmit(event) {
      // prevent enter key from submitting form
      var event = event || window.event;
      if (event.keyCode == 13) {
        return false;
      }
    }

   function getTarget( event ) {
     var e = event || window.event;
    
     if( e.target )
         return e.target;
      else
         return e.srcElement;
}

   function stopPropagation( event ) {
  
      if( event.stopPropagation )
         event.stopPropagation();
        
      if( event.preventDefault )
        event.preventDefault();

     if( event.cancelBubble)
       event.cancelBubble = true;

    if(event.returnValue)
       event.returnValue = false;

    return false;
}

//--><!]]>
  </script>

CSS Source Code

  <style type="text/css">
div.text,
div.textinvalid,
div.button
{
  margin: 0;
  padding: 0;
  padding-left: 20px;
  padding-bottom: .5em;
  display: block;
}

div.text label,
div.textinvalid label {
margin: 0;
padding: 0;
display: block;
padding-top: .25em;
}

div.text label span.required {
  font-size: 70%;
  font-weight: bold;
  color: blue;
}

div.text input,
div.textinvalid input {
margin: 0;
padding: 0;
display: inline;
}

span.inst {
  font-size: 75%;
  color: blue;
  padding-left: .25em;
}

div.text input:active,
div.text input:focus,
div.text input:hover
{
  border-color: gray;
  background-color: #E0E0E0;
}






  </style>