In this article I will explain with an example, how to validate at-least one TextBox from Multiple TextBoxes in ASP.Net.
The at-least one TextBox validation will be performed using JavaScript and ASP.Net CustomValidator in ASP.Net.
HTML Markup
The HTML Markup consists of multiple ASP.Net TextBoxes, a CustomValidator and a Button. The ASP.Net CustomValidator has been assigned with ClientValidationFunction property in which the name of JavaScript function has been specified which will perform the validation.
<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:CustomValidator ErrorMessage="Please enter at-least one Address proof." runat="server" ForeColor="Red" ClientValidationFunction="ValidateAddressProof" />
</td>
</tr>
<tr>
<td></td>
<td><asp:Button Text="Submit" runat="server" /></td>
</tr>
</table>
The ClientValidationFunction JavaScript function
Inside the ClientValidationFunction JavaScript function, first the TextBoxes are referenced and their values are fetched in respective labels.
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 validation is set OK with the help of args.IsValid property set to True and it is failed by setting the args.IsValid property to False.
<script type="text/javascript">
function ValidateAddressProof(sender, args) {
//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;
//Check if Passport Number is not blank.
if (passport.trim() != "") {
args.IsValid = true;
return;
}
//Check if Aadhar Number is not blank.
if (aadhar.trim() != "") {
args.IsValid = true;
return;
}
//Check if PAN Number is not blank.
if (pan.trim() != "") {
args.IsValid = true;
return;
}
args.IsValid = false;
}
</script>
Screenshot
Demo
Downloads