JavaScript Form Processing

Unobtrusive Error Handling

The main purpose in validating a form using JavaScript is so that we can display an error message as soon as possible after a mistake is made in entering data into the form. we also want to prevent the form being submitted when our JavaScript detects an error so that the error can be fixed without needing a round trip to the server and back.

The old option of using alert() is no longer suitable since it is now intended primarily as a debugging tool and some browsers now provide an option within an alert to turn JavaScript off for the web page - definitely something we don't want to have happen.

There are two things we need to add to the unobtrusive validation processing that we have already discussed in order to be able to do this. We need an unobtrusive error message field in our form and we need a way to prevent subsequent processing from occurring (such as the form being submitted).

To add an obvious spot for messages to appear in our form we could add the following HTML into the form so as to give us a place to display the messages.


<fieldset>
<legend>Message</legend>
<div id="message"> </div>
</fieldset>

With that code in place we can then update the form to display any required message by calling the following function.


errorMessage = function(mes) {
  document.getElementById('message').innerHTML = mes;
}

This makes it really easy to change how we process the error messages at any future time simply by amending that HTML and JavaScript function without needing to touch any of the rest of our code.

When we were using event handlers we could simply return false from functions to prevent any default processing from occurring. With event handlers returning false can still be used to prevent any subsequent JavaScript from running but will not prevent the default action in the HTML from occurring.

To be able to do that as well we will need to add an extra function call before we return false to the following function which distinguishes between the standard event listeners and the IE proprietary processing to use whichever one is needed in order to prevent the default action occurring.


stopDef = function(e) {
if (e && e.preventDefault)
  e.preventDefault();
else if (window.event && window.event.returnValue)
  window.eventReturnValue = false;
};

With that code in place we can then perform our validations using if statements that will evaluate as true when the input is invalid using the following code.


if (invalid) {
  errorMessage('error message goes here');
  stopDef();
  return false;
}