public class CheckBoxRequired : ValidationAttribute, IClientModelValidator
{
public override bool IsValid(object value)
{
if (value is bool)
{
return (bool)value;
}
return false;
}
public void AddValidation(ClientModelValidationContext context)
{
context.Attributes.Add("data-val-checkboxrequired", FormatErrorMessage(context.ModelMetadata.GetDisplayName()));
}
}
public class PersonModel
{
[Display(Name = "I accept the above terms and conditions.")]
[CheckBoxRequired(ErrorMessage = "Please accept the terms and condition.")]
public bool TermsConditions { get; set; }
}
<script type="text/javascript">
(function ($) {
$.validator.unobtrusive.adapters.addBool("checkboxrequired", "required");
}(jQuery));
</script>
參考文獻
aspsnippets