Description:
In this example
we explain that how to validate CheckBox in Razor View in MVC.or client side
validation for the CheckBox in MVC Razor using jQuery. Or how to perform client
side validation for CheckBox in Asp.Net MVC Razor using jQuery.
Here we
demonstrate that how to perform client side validation for the CheckBox using
Model class and Data Annotation attributes in MVC.
Custom validator:
public class CheckBoxRequired
: ValidationAttribute, IClientValidatable
{
public override bool
IsValid(object value)
{
if
(value isbool)
{
return
(bool)value;
}
return false;
}
public IEnumerable<ModelClientValidationRule>
GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new
ModelClientValidationRule
{
ErrorMessage =
FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "checkboxrequired"
};
}
}
Model:
public class EmployeeModel
{
[Display(Name = "I accept the above terms and conditions.")]
[CheckBoxRequired(ErrorMessage = "Please accept the terms and condition.")]
public bool
TermsConditions { get; set;
}
}
Controller:
public class EmployeeController
: Controller
{
// GET: Home
public ActionResult Index()
{
return
View();
}
[HttpPost]
public ActionResult Index(PersonModel person)
{
return
View();
}
}
View:
@model
CheckBox_Validation_MVC.Models.EmployeeModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Client
Side CheckBox validation in ASP.Net MVC Razor using jQuery</title>
</head>
<body>
@using (Html.BeginForm("Index",
"Employee", FormMethod.Post))
{
<table>
<tr>
<td>@Html.CheckBoxFor(m
=> m.TermsConditions)</td>
<td>@Html.LabelFor(m
=> m.TermsConditions)</td>
</tr>
<tr>
<td></td>
<td>
@Html.ValidationMessageFor(m => m.TermsConditions, "", new
{ @class = "error" })
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit"/></td>
</tr>
</table>
}
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
(function
($) {
$.validator.unobtrusive.adapters.addBool("checkboxrequired",
"required");
} (jQuery));
</script>
</body>
</html>
0 comments:
Post a Comment