<script type="text/javascript">
jQuery.validator.addMethod("mustbetrue", function (value, element, param) {
return element.checked;
});
jQuery.validator.unobtrusive.adapters.addBool("mustbetrue", "required");
这是我的脚本和c#代码是......
public class mustbetrueAttribute : ValidationAttribute, IClientValidatable // IClientValidatable for client side Validation
{
public bool chkbox { get; set; }
public override bool IsValid(object value)
{
if (value is bool)
return (bool)value;
else
return false;
}
// Implement IClientValidatable for client side Validation
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var modelClientValidationRule = new ModelClientValidationRule
{
ValidationType = "mustbetrue",
ErrorMessage = FormatErrorMessage(metadata.DisplayName)
};
modelClientValidationRule.ValidationParameters.Add("mustbetrue", chkbox);
yield return modelClientValidationRule;
//return new ModelClientValidationRule[] { new ModelClientValidationRule { ValidationType = "checkbox", ErrorMessage = this.ErrorMessage } };
//yield return new ModelClientValidationRule
//{
// ErrorMessage = "You must accept Terms and Condition",
// //Given Validation Type will be Used for Client side Validation in Unobtrusive Jquery
// ValidationType = "mustbetrue"
//};
}
}
渲染html:
<li>
<label for="TermsAccepted">Terms and Conditions.</label>
<input data-val="true" data-val-mustbetrue="Please Accept the Terms & Conditions" data-val-mustbetrue-mustbetrue="False" data-val-required="The Terms and Conditions. field is required." id="TermsAccepted" name="TermsAccepted" type="checkbox" value="true" />
<input name="TermsAccepted" type="hidden" value="false" />
</li>
答案 0 :(得分:0)