FORM Validation by JavaScript

This page shows how to validate a form field using JavaScript. You should be familiar with HTML form. If not, see this tutorial: HTML Form Sample.

Here is a dummy field:

Type the last English alphabet here then press tab to move the focus away:

If you typed wrong, it will popup a alert box telling you so.

Here's the code:

<input id="x" type="text" size="1" maxlength="1" name="alphabet">
var tt = document.getElementById("x");

function checkIt() {
  if (tt.value != 'z') {
    alert('You twit! You should have typed “z”.');
    return false;
  } else {
    alert('O, you are so smart!');
    return true;
  }
}

tt.onblur=checkIt;

This validation is based on the onBlur event. It validates dynamically on a per field basis. It is quite simple. However, it doesn't prevent user from pressing the submit button with invalid values in the field. The JavaScript technique is only for user convenience.

For validation that actually prevent the form being submitted, see: HTML FORM Validation


Related Essays:

2005-12
© 2005 by Xah Lee.