我正在尝试实现this post中提到的代码。换句话说,我正在尝试在条款和条件复选框上实现不打扰的验证。如果用户未选中该复选框,则应将输入标记为无效。

这是服务器端验证程序代码,我添加了:

/// <summary>
/// Validation attribute that demands that a boolean value must be true.
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class MustBeTrueAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        return value != null && value is bool && (bool)value;
    }
}

这是模特
[MustBeTrue(ErrorMessage = "You must accept the terms and conditions")]
[DisplayName("Accept terms and conditions")]
public bool AcceptsTerms { get; set; }

这是我的看法:
@Html.EditorFor(x => x.AcceptTermsAndConditions)
@Html.LabelFor(x => x.AcceptTermsAndConditions)
@Html.ValidationMessageFor(x => x.AcceptTermsAndConditions)

这是我用来附加验证器客户端的jQuery:
$.validator.unobtrusive.adapters.addBool("mustbetrue", "required");

但是,客户端脚本似乎没有启动。每当我按下“提交”按钮时,其他字段上的验证就会启动,但条款和条件的验证似乎无法启动。这就是我单击“提交”按钮后代码在Firebug中的显示方式。
<input type="checkbox" value="true" name="AcceptTermsAndConditions" id="AcceptTermsAndConditions" data-val-required="The I confirm that I am authorised to join this website and I accept the terms and conditions field is required." data-val="true" class="check-box">
<input type="hidden" value="false" name="AcceptTermsAndConditions">
<label for="AcceptTermsAndConditions">I confirm that I am authorised to join this website and I accept the terms and conditions</label>
<span data-valmsg-replace="true" data-valmsg-for="AcceptTermsAndConditions" class="field-validation-valid"></span>

有任何想法吗?我错过了一步吗?这让我上厕所了!

提前致谢
小号

最佳答案

嗅探器

除了实现Darin的解决方案之外,您还需要修改jquery.validate.unobtrusive.js文件。在此文件中,必须添加“mustbetrue”验证方法,如下所示:

$jQval.addMethod("mustbetrue", function (value, element, param) {
    // check if dependency is met
    if (!this.depend(param, element))
        return "dependency-mismatch";
    return element.checked;
});

然后(我首先忘记添加此内容),还必须将以下内容添加到jquery.validate.unobtrusive.js:
adapters.add("mustbetrue", function (options) {
    setValidationValues(options, "mustbetrue", true);
});

法律顾问

关于asp.net-mvc-3 - MVC复选框上的非侵入式验证不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6923430/

10-11 23:01
查看更多