JSFiddle - React, Tailwind, and code Playground

by willslab

HTML

<form>
    <label for="userAge">Age:</label>
    <input type="text" name="userAge" id="userAge" />
    <input type="button" id="test" name="test" value="Test" />
</form>

JavaScript

function validateForm() {

    // get the input value once and use a variable
    // this makes the rest of the code more readable
    // and has a small performance benefit in retrieving
    // the input value once
    var userAge = document.forms[0].userAge.value;
    
    // is it blank?
    if (userAge === "") {
        alert("Age field cannot be empty.")
        return false;
    }
    
    // is it a valid number? testing for positive integers
    if (!userAge.match(/^\d+$/)) {
        alert("Your age input is not correct.")
        return false;
    }

    // you could also test parseInt(userAge, 10) < 5
    if (userAge < 5) {
        alert("Your age input is not correct.")
        return false;
    }

    alert("Name and Age are valid.");
    return true;
}

document.getElementById("test").onclick = validateForm;