In this article I will explain with an example, how to validate at-least one TextBox from multiple TextBoxes in ASP.Net MVC using jQuery.
Controller
The Controller consists of following Action method.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
}
View
The View consists of multiple TextBoxes and a Label created using MVC Helper method and a HTML INPUT 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 Label element.
@{
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>@Html.TextBox("txtPassport")</td>
</tr>
<tr>
<td>Aadhar Number</td>
<td>@Html.TextBox("txtAadhar")</td>
</tr>
<tr>
<td>PAN Number</td>
<td>@Html.TextBox("txtPAN")</td>
</tr>
<tr>
<td colspan="2">
@Html.Label("", "Please enter at-least one Address proof.",
new { @style = "color: Red; visibility: hidden;", @id = "lblMessage" })
</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 Label 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