Introduction
Often in a form, there's the need to insert only an input or two and make checks on them. Here, I'll show how to do this with HTML5 form validation without jQuery or other frameworks.
Background
To understand this trick, you should know how HTML5 form validation works and a bit of JavaScript.
Using the Code
Here a part of HTML form made with bootstrap:
<div class="row-fluid">
<div class="span3">
<label>Cell</label>
<input type="text" style="width:90%"
placeholder="Cell" name="cell"
onchange="TelCell(this)" required
title="Insert a good cell number" x-moz-errormessage="
Insert a good cell number" pattern="[0-9]+">
</div>
<div class="span3">
<label>Tel</label>
<input type="text" style="width:95%"
placeholder="Phone" name="tel"
onchange="TelCell(this)" required
pattern="[0-9]+" title="Insert a good phone number"
x-moz-errormessage="Insert a good phone number" >
</div>
</div>
Here, you can see that there's the input change event that calls the TelCell
function, and inputs are both required.
Here is the JavaScript code:
function TelCell(objInput) {
var divFather = objInput.parentNode.parentNode;
var children = divFather.querySelectorAll("input");
var sibling;
if(children[0].name == objInput.name)
sibling = children[1];
else
sibling = children[0];
if(objInput.value.trim() != "" && objInput.checkValidity() == true) {
sibling.removeAttribute("required");
} else {
if(sibling.value.trim() != "" && sibling.checkValidity() == true) {
sibling.setAttribute("required", "required");
objInput.removeAttribute("required");
} else {
objInput.setAttribute("required", "required");
sibling.setAttribute("required", "required");
}
}
}
I hope that something like this can be made in default with a future HTML version.