asp.net-mvc-3 – 对复选框不起作用的MVC不显眼的验证

前端之家收集整理的这篇文章主要介绍了asp.net-mvc-3 – 对复选框不起作用的MVC不显眼的验证前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图实现 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>

有任何想法吗?我错过了一步吗?这是驱使我的便盆!

提前致谢
S

解决方法

嗅探器,

除了实现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相关文章