MVC3不引人注目的验证扩展;条款和条件复选框

时间:2012-05-31 15:31:36

标签: asp.net-mvc-3 unobtrusive-validation

我见过其他一些帖子:

MVC unobtrusive validation on checkbox not working

MVC3: make checkbox required via jQuery validate?

但是我已经实现了它们,并且无法弄清楚为什么我的验证无法正常工作:

属性:

[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>

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

1 个答案:

答案 0 :(得分: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;
        }
    }
});