MVC5剃须刀中的Checkbox自定义验证

时间:2014-08-01 19:15:10

标签: c# razor asp.net-mvc-5 data-annotations

我正在尝试为视图强制显示所需的条款和条件。我按照此论坛上列出的代码示例进行了操作:http://www.dotnet-tricks.com/Tutorial/mvc/8UFa191212-Custom-Validation-for-Checkbox-in-MVC-Razor.html但是如果我在IsValid方法中设置断点,它是否永远不会到达。此外,ModelState.IsValid应为false时返回true;如果从未选中该复选框。

以下是ViewModel的代码:

public class TermsConditionViewModel
{
    [MustBeTrue(ErrorMessage = "The terms and conditions must be read and agreed to complete the registration process.")]
    [Display(Name = "")]
    public bool TermsConditionsCompleted { get; set; }
} 

以下是自定义数据注释的代码:

public class MustBeTrueAttribute : ValidationAttribute, IClientValidatable // IClientValidatable for client side Validation
{
    public override bool IsValid(object value)
    {
        return value is bool && (bool)value;
    }
    // Implement IClientValidatable for client side Validation
    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        return new ModelClientValidationRule[] { new ModelClientValidationRule { ValidationType = "checkbox", ErrorMessage = this.ErrorMessage } };
    }


}

public class MustBeSelected : ValidationAttribute, IClientValidatable // IClientValidatable for client side Validation
{
    public override bool IsValid(object value)
    {
        if (value == null || (int)value == 0)
            return false;
        else
            return true;
    }
    // Implement IClientValidatable for client side Validation
    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        return new ModelClientValidationRule[] { new ModelClientValidationRule { ValidationType = "dropdown", ErrorMessage = this.ErrorMessage } };
    }
}

以下是客户端验证的JavaScript代码

$.validator.unobtrusive.adapters.add("dropdown", function (options) {
//  debugger;
if (options.element.tagName.toUpperCase() == "SELECT" && options.element.type.toUpperCase() == "SELECT-ONE") {
    options.rules["required"] = true;
    if (options.message) {
        options.messages["required"] = options.message;
    }
}
});

$.validator.unobtrusive.adapters.add("checkbox", 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;
    }
}
});

这是生成的标记

<input data-val="true" data-val-checkbox="The terms and conditions must be read and agreed to complete the registration process." data-val-required="The  field is required." id="TermsConditionsCompleted" name="TermsConditionsCompleted" type="checkbox" value="true" /><input name="TermsConditionsCompleted" type="hidden" value="false" />&nbsp;I have read and agree with the terms and conditions described above

是否需要进行额外配置才能实现此功能?到目前为止我找到的所有示例似乎都设置相同,Web.Config,Global.asax等中没有配置。

2 个答案:

答案 0 :(得分:0)

您缺少一些jQuery验证步骤。 我已经按照此链接上的路径解决了相同的问题并完成了相同的任务: http://www.yogihosting.com/client-side-validation-asp-net-mvc/

希望它对您有帮助。

亚历山德罗

答案 1 :(得分:-2)

你的解决方案看起来真的有点过头了,相反,我只是在表单提交上添加一个jQuery方法,确保选中该复选框。

更少的代码。