Submodule 9.3: Form validation
5. The input type="text" element
The below code creates the validation for the input type="text".
It displays the appropriate png icons and the appropriate message in the span area with id " firstnameInfo".
The HTML code:
<div class = "required">
<label for="firstname">First name:</label>
<input type="text" name="firstname" id="firstname" class = "required"
placeholder="Your first name goes here"
autofocus="autofocus" minlength="4" required />
<span id="firstnameInfo"></span>
</div>
and the JavaScript code:
<script>
var myfirsname = document.getElementById("firstname");
var myfirstnameInfo = document.getElementById("firstnameInfo");
myfirsname.oninput = function () {
if (!this.validity.valid) {myfirsname.style.backgroundImage= "url(images/invalid.png) " ;
myfirsname.style.backgroundRepeat= " no-repeat";
myfirsname.style.backgroundPosition= " right top";
myfirstnameInfo.innerHTML = "Your name is too small."
}
else {
myfirsname.style.backgroundImage= "url(images/valid.png) " ;
myfirsname.style.backgroundRepeat= " no-repeat";
myfirsname.style.backgroundPosition= " right top";
myfirstnameInfo.style.display = "none";
}
}
</script>
will create an input displayed as: