In this article I will explain with an example, how to validate at-least one TextBox from multiple TextBoxes in ASP.Net Core Razor Pages.
The validations will be performed using jQuery.
Razor PageModel (Code-Behind)
The PageModel consists of following Handler method.
Handler method for handling GET operation
This Handler method handles the GET calls, for this particular example it is not required and hence left empty.
public class IndexModel : PageModel
{
public void OnGet()
{
}
}
Razor Page (HTML)
The HTML of Razor Page consists of multiple HTML TextBoxes and HTML SPAN element and a Button element.
Implementing validation using jQuery
Inside the jQuery document ready event handler, the Button has been assigned a Click event handler.
Inside the Click event handler, 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 SPAN element.
@page
@model Validate_AtLeast_TextBox_jQuery_Razor_Core.Pages.IndexModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<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 id="btnSubmit" type="button" value="Submit" /></td>
</tr>
</table>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnSubmit").on("click", function () {
//Referencing and fetching the TextBox values.
var passport = $("#txtPassport").val();
var aadhar = $("#txtAadhar").val();
var pan = $("#txtPAN").val();
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.
$("#lblMessage").css("visibility", !isValid ? "visible" : "hidden");
});
});
</script>
</body>
</html>
Screenshot
Browser Compatibility
The above code has been tested in the following browsers.
* All browser logos displayed above are property of their respective owners.
Downloads