JavaScript: Instant Form Field Validation

By Xah Lee. Date: . Last updated: .

2019-06-26 this page is outdated. Kept here for history purpose.

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

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

Here is the JavaScript code:

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

let 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 .

BUY
ΣJS
JavaScript in Depth