不能够显示客户端验证消息,但是它可以在表单验证上工作
本文关键字:验证 表单 工作 客户端 显示 消息 不能够 | 更新日期: 2023-09-27 18:13:10
<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>
你忘了添加:
$.validator.addClassRules("mustbetrue", {
mustbetrue: true
});
下面是一个示例