2

我还看过其他一些关于此的帖子:

复选框上的 MVC 不显眼验证不起作用

MVC3:通过 jQuery 验证使复选框需要?

但是我已经实现了它们并且不能完全弄清楚为什么我的验证不能正常工作:

属性:

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public sealed class MustBeTrueAttribute : ValidationAttribute, IClientValidatable {
        public override bool IsValid(object value) {
            return value != null && (bool)value;
        }

        public override string FormatErrorMessage(string name) {
            return string.Format("The {0} field must be true.", name);
        }

        #region Implementation of IClientValidatable

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) {
            yield return new ModelClientValidationRule {
                ErrorMessage = string.IsNullOrEmpty(ErrorMessage) ? FormatErrorMessage(metadata.DisplayName) : ErrorMessage,
                ValidationType = "mustbetrue"
            };
        }

        #endregion
    }

适配器扩展:

// Unobtrusive validation extras
$.validator.unobtrusive.adapters.addBool("mustbetrue", function (options) {
    //b-required for checkboxes
    if (options.element.tagName.toUpperCase() == "INPUT" && options.element.type.toUpperCase() == "CHECKBOX") {
        options.rules["required"] = true;
        if (options.message) {
            options.messages["required"] = options.message;
        }
    }
});

模型属性:

    [Display(Name = "I agree to RustyShark's Terms of Use")]
    [MustBeTrueAttribute(ErrorMessage = "You must agree to the Terms of Use")]
    public bool AgreeToTerms { get; set; }

看法:

<div class="formField">
    <div class="label">
        @Html.LabelFor(m => m.AgreeToTerms); @Html.ActionLink("view here", "TermsOfUse", "Home", null, new { target = "_blank" }).
    </div>
    <div class="input">
        @Html.CheckBoxFor(m => m.AgreeToTerms)
    </div>
    @Html.ValidationMessageFor(m => m.AgreeToTerms)
</div>

呈现以下 HTML:

<div class="formField">
    <div class="label">
        <label for="AgreeToTerms">I agree to RustyShark's Terms of Use</label>; <a href="/Home/TermsOfUse" target="_blank">view here</a>.
    </div>
    <div class="input">
        <input data-val="true" data-val-mustbetrue="You must agree to the Terms of Use" data-val-required="The I agree to RustyShark&amp;#39;s Terms of Use field is required." id="AgreeToTerms" name="AgreeToTerms" type="checkbox" value="true" class="valid"><input name="AgreeToTerms" type="hidden" value="false">
    </div>
    <span class="field-validation-valid" data-valmsg-for="AgreeToTerms" data-valmsg-replace="true"></span>
</div>

服务器端验证正在工作(虽然它返回的是默认错误消息,而不是被覆盖的错误消息),但客户端没有 - 我只是没有收到任何消息,但一切都在正确执行?谁能看到我的问题?

4

1 回答 1

4

终于想通了!

主要问题是我在 $(document).ready() 函数中执行 $.validator 方法。它需要作为内联函数执行!我只是将它们移到了 ready() 之外,事情就开始发生了!

此外,JS 应如下所示:

$.validator.addMethod("mustbetrue", function (value, element, params) {
    return value == true;
});
$.validator.unobtrusive.adapters.add("mustbetrue", function (options) {
    if (options.element.tagName.toUpperCase() == "INPUT" && options.element.type.toUpperCase() == "CHECKBOX") {
        options.rules["required"] = true;
        if (options.message) {
            options.messages["required"] = options.message;
        }
    }
});
于 2012-05-31T18:46:19.290 回答