Form Handling - The Validity Property

by somya_kashyap3

HTML

<h3>HTML Input element 'validity' property</h3>

<b>Open your console to see the output of this code</b>
<p>Validity checking a matter of using events, object properties, conditionals, and writing to the DOM. </p>

<p>(The range attributes on the 'age' input field are set to accept between 18 and 34.)</p>
<form action="#" id="theForm" name="firstForm">
    <label for="age">Age:</label>
    <input type="number" id="age" name="age" size="8" min="18" max="34" /> <span id="agehint"></span>
    <bhttp://jsfiddle.net/#saver/>
    <button type="submit" name="submit">Submit</button>
</form>

JavaScript

var ageInput = document.forms[0].age;
var ageHint = document.getElementById("agehint");

/*  This onchange handler will run every time you change the value of 'age' (even as you type).    */
ageInput.addEventListener("input", function () {
    // We check the element's 'validity' property, 
    //  which will be 'valid' or some other value 
    //  (the specific kind of invalid depends on the constraint)
    
    if (!this.validity.valid) {
        // For min/max constraints, 
        //  rangeUnderflow or rangeOverflow apply
        console.log("Too high: " + this.validity.typeMismatch);
        console.log("Too low: " + this.validity.rangeUnderflow);

        //output a useful message
        if (this.validity.rangeOverflow) {
            agehint.innerHTML = 'Number is too high';
        } else if (this.validity.rangeUnderflow) {
            agehint.innerHTML = 'Number is too low';
        }
    }else{
        // don't forget to clear hint if the input becomes valid!
        agehint.innerHTML = '';
    }
});