In this article I will explain with an example, how to validate at-least one TextBox from multiple TextBoxes in JavaScript.
This particular technique can be used in various technologies like ASP.Net Web Forms, ASP.Net MVC and .Net Core.
HTML Markup
The HTML Markup consists of multiple HTML TextBoxes, HTML SPAN element and a Button.
The Button which has been assigned an OnClick event handler.
<table>
<tr>
<th colspan="2">Address Proofs (At-least one)</th>
</tr>
<tr>
<td>Passport Number</td>
<td><input id="txtPassport" type="text" /></td>
</tr>
<tr>
<td>Aadhar Number</td>
<td><input id="txtAadhar" type="text" /></td>
</tr>
<tr>
<td>PAN Number</td>
<td><input id="txtPAN" type="text" /></td>
</tr>
<tr>
<td colspan="2">
<span id="lblMessage" style="color: Red; visibility: hidden;">
Please enter at-least one Address proof.
</span>
</td>
</tr>
<tr>
<td></td>
<td><input type="button" value="Submit" onclick="ValidateAddressProof()" /></td>
</tr>
</table>
Implementing validation using JavaScript
Inside the ValidateAddressProof JavaScript function, first the TextBoxes are referenced and their values are fetched in respective variables.
Then, a check is performed one by one for each value of Passport number, Aadhar number and PAN number respectively. If at-least one of them has value then the validation is passed else the validation fails.
The isValid variable set to True or False based on whether the validation is passed or failed respectively.
Finally, based on the isValid variable, the result is displayed in the HTML SPAN element.
<script type="text/javascript">
function ValidateAddressProof() {
//Referencing and fetching the TextBox values.
var passport = document.getElementById("txtPassport").value;
var aadhar = document.getElementById("txtAadhar").value;
var pan = document.getElementById("txtPAN").value;
var isValid = false;
//Check if Passport Number is not blank.
if (passport.trim() != "") {
isValid = true;
}
//Check if Aadhar Number is not blank.
if (aadhar.trim() != "") {
isValid = true;
}
//Check if PAN Number is not blank.
if (pan.trim() != "") {
isValid = true;
}
//Show or hide HTML SPAN based on IsValid variable.
document.getElementById("lblMessage").style.visibility = !isValid ? "visible" : "hidden";
}
</script>
Screenshot
Browser Compatibility
The above code has been tested in the following browsers.
* All browser logos displayed above are property of their respective owners.
Demo
Downloads