MathCurvesSurfacesWallpaper GroupsGallerySoftwarePOV-Ray
ProgramingLinuxPerl PythonHTMLCSSJavaScriptPHPJavaLang DesignEmacsUnicode ♥

Instant Form Field Validation By JavaScript

, 2005-12, 2011-01

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.

Type the last letter of English alphabet here then press Tab ↹ key.

If you did not type z, it will popup a alert box telling you so.

Here's how to do it.

First, use the “input” to create a form, with a “id” attribute, so that this box can be identified by the js.

<input id="x" type="text" size="1" maxlength="1" name="alphabet">

Here's the JavaScript code that adds behavior to the input box:

var tt = document.getElementById("x");

function checkIt() {
  if (tt.value != 'z') {
    alert('You twit! You should have typed “z”.');
    return false;
  } else {
    alert('You are the one!');
    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.

blog comments powered by Disqus