<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 = '';
}
});
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.