In this article I will explain with an example, how to validate at-least one TextBox from multiple TextBoxes in ASP.Net using JavaScript.
HTML Markup
The HTML Markup consists of multiple ASP.Net TextBoxes, Label and a Button control.
The ASP.Net Button has been assigned a JavaScript OnClientClick event handler.
<table>
<tr>
<th colspan="2">Address Proofs (At-least one)</th>
</tr>
<tr>
<td>Passport Number</td>
<td><asp:TextBox ID="txtPassport" runat="server" /></td>
</tr>
<tr>
<td>Aadhar Number</td>
<td><asp:TextBox ID="txtAadhar" runat="server" /></td>
</tr>
<tr>
<td>PAN Number</td>
<td><asp:TextBox ID="txtPAN" runat="server" /></td>
</tr>
<tr>
<td colspan="2">
<asp:Label ID="lblMessage" runat="server" Style="color: Red; visibility: hidden;">
Please enter at-least one Address proof.
</asp:Label>
</td>
</tr>
<tr>
<td></td>
<td><asp:Button Text="Submit" runat="server" OnClientClick="return ValidateAddressProof();" /></td>
</tr>
</table>
Implementing validation in ASP.Net 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 Label control.
<script type="text/javascript">
function ValidateAddressProof() {
//Referencing and fetching the TextBox values.
var passport = document.getElementById("<%=txtPassport.ClientID%>").value;
var aadhar = document.getElementById("<%=txtAadhar.ClientID%>").value;
var pan = document.getElementById("<%=txtPAN.ClientID%>").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 Label based on isValid variable.
document.getElementById("<%=lblMessage.ClientID%>").style.visibility = !isValid ? "visible" : "hidden";
return false;
}
</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