validate.unobtrusive.js,无法显示客户端验证消息,但它适用于表单验证

时间:2015-09-17 08:16:14

标签: javascript c# asp.net-mvc validation unobtrusive-validation

<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 &amp; 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>

1 个答案:

答案 0 :(得分:0)

你忘记添加:

$.validator.addClassRules("mustbetrue", {
    mustbetrue: true
});

这是jsfiddle with example