Hi mahesh213,
You need to write all the checking in on function and call it on each textbox onblur event.
Refer below code.
Model
public class Category
{
public string Name { get; set; }
public string Age { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
Controller
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View(new Category());
}
}
View
@model Validate_Multiple_TextBox_MVC.Models.Category
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
function Validate() {
if (!$('#txtName').val()) {
if ($("#txtName").next(".validation").length == 0) {
$("#txtName").after("<div class='validation' style='color:red;'>Name is Required</div>");
return false;
}
} else {
$("#txtName").next(".validation").remove();
}
if (!$('#txtAge').val()) {
if ($("#txtAge").next(".validation").length == 0) {
$("#txtAge").after("<div class='validation' style='color:red;'>Age is Required</div>");
return false;
}
} else {
$("#txtAge").next(".validation").remove();
}
if (!$('#txtCity').val()) {
if ($("#txtCity").next(".validation").length == 0) {
$("#txtCity").after("<div class='validation' style='color:red;'>City is Required</div>");
return false;
}
} else {
$("#txtCity").next(".validation").remove();
}
if (!$('#txtCountry').val()) {
if ($("#txtCountry").next(".validation").length == 0) {
$("#txtCountry").after("<div class='validation' style='color:red;'>Country is Required</div>");
return false;
}
} else {
$("#txtCountry").next(".validation").remove();
}
}
</script>
</head>
<body>
@Html.TextBoxFor(a => a.Name, new { @id = "txtName", @onblur = "return Validate()" })
<br />
@Html.TextBoxFor(a => a.Age, new { @id = "txtAge", @onblur = "return Validate()" })
<br />
@Html.TextBoxFor(a => a.City, new { @id = "txtCity", @onblur = "return Validate()" })
<br />
@Html.TextBoxFor(a => a.Country, new { @id = "txtCountry", @onblur = "return Validate()" })
</body>
</html>