JS: Instant Form Field Validation

By Xah Lee. Date: . Last updated: .

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 the HTML code:

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

Here's the JavaScript code:

function checkValue(ele) {
    if (ele.value != "z") {
        alert("wrong! You should have typed z.")
        return false
    } else {
        alert("good")
        return true
    }
}

var node = document.getElementById("input07004");

node.addEventListener("blur", function () { checkValue(node)} , false);

This validation is based on the “blur” 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.

Like what you read? Buy JavaScript in Depth