复选框上的 MVC 非侵入式验证不起作用

MVC unobtrusive validation on checkbox not working

提问人:Sniffer 提问时间:8/3/2011 最后编辑:CommunitySniffer 更新时间:11/5/2019 访问量:27195

问:

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

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

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

asp.net-mvc-3 剃刀 javascript 不显眼- 验证

评论

0赞 Fred 3/31/2016
你不能只使用属性而不是创建自己的属性吗?[Requred]MustBeTrueAttribute

答:

37赞 Darin Dimitrov 8/3/2011 #1

您需要在自定义属性上实现 IClientValidatable,以便将客户端注册的适配器名称与此属性相关联:mustbetrue

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

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        yield return new ModelClientValidationRule
        {
            ErrorMessage = this.ErrorMessage,
            ValidationType = "mustbetrue"
        };
    }
}

更新:

完整的工作示例。

型:

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

控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel();
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        return View(model);
    }
}

视图:

@model MyViewModel

<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script type="text/javascript">
    $.validator.unobtrusive.adapters.addBool("mustbetrue", "required");
</script>

@using (Html.BeginForm())
{
    @Html.CheckBoxFor(x => x.AcceptsTerms)
    @Html.LabelFor(x => x.AcceptsTerms)
    @Html.ValidationMessageFor(x => x.AcceptsTerms)
    <input type="submit" value="OK" />
}

评论

0赞 Sniffer 8/3/2011
我虽然你在那里有它,Dann(你肯定让我走得更远),但它在客户端仍然不起作用。javascript 正确吗?$.validator.unobtrusive.adapters.addBool(“mustbetrue”, “必需”);
0赞 Sniffer 8/3/2011
丹恩 - 我已经做了这一切,但我仍然无法让我的例子发挥作用。问题是无论如何,输入的 HTML 始终保持不变(请参阅原始问题中的 html,尽管现在出现了 data-val-mustbetrue!无论如何,data-val 始终设置为 true - 即使在页面加载时也是如此。这是你所期望的吗?我什至将我的 javascript 更改为 $.validator.unobtrusive.adapters.addBool(“mustbetrue”);并且我仍然在 HTML 中获得 data-val-required 属性,这是我没想到的......有什么想法吗?
1赞 Darin Dimitrov 8/3/2011
@Sniffer,你将获得 data-val-required 属性,因为你的 AcceptsTerms 属性是不可为 null 的布尔属性,因此 MVC 会自动追加它 ASP.NET。这是预期行为。
3赞 marapet 1/25/2013
效果很好!为了在客户端使用本地化的错误消息(带有 和 )而不是默认的必需消息,我必须将 Attribute 定义中的一行更改为ErrorMessageResourceTypeErrorMessageResourceNameErrorMessage = FormatErrorMessage(metadata.DisplayName),
5赞 Hugo Hilário 3/20/2014
只是在此处添加的有用信息。这条线必须像季米特洛夫一样添加到里面。例如,如果您将其添加到其中,它将不起作用。而且您不需要在 jquery.validate.unobtrusive 文件上添加任何内容。$.validator.unobtrusive.adapters.addBool("mustbetrue", "required");<script type="text/javascript">$(document).ready(function () {
26赞 counsellorben 8/4/2011 #2

嗅探器

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

$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);
});

辅导员本

评论

0赞 Sniffer 8/4/2011
这太棒了,我错过了什么!明。希望我能把你和达林都标记为答案,但你明白了,就像你让我越过终点线一样!最后一个问题要整理一下 - 有没有办法添加这 2 段代码而不必更改核心不显眼的 .js 脚本?我尝试将 $jQval.addMehod 更改为 $.validator.addMethod 并将 adapters.add 更改为 $.validator.unobtrusive.adapters.add 并从外部脚本文件调用它们,但这似乎不起作用。有什么想法吗?
0赞 Sniffer 8/4/2011
啊,抱歉 - 我在那里有点偏离了目标。它不太有效。现在,如果复选框未勾选,则验证将显示为错误(太好了!),但如果用户随后去检查复选框,验证仍然显示为无效(不是很好!)。现在,这会阻止页面回发,因为它认为仍然存在错误。有什么想法吗?
1赞 counsellorben 8/4/2011
@Sniffer,对不起,但当我认为自己很圆滑并且不仔细检查时,就会发生这种情况。“return this.checked;”行不正确,我已经更改了它。我尝试了几种方法将脚本插入页面,而不是修改jquery.validate.unobtrusive.js,但没有一种方法成功。
0赞 Sniffer 8/4/2011
我可以吻你(但我显然不会)!element.checked 工作得很愉快!奇怪的是,如果不直接更改jquery.validate.unobtrusive.js,就无法添加脚本。我会再玩一会儿 - 也许值得单独提出 SO 问题。无论如何,如果我找到方法,我会在这里发布更新。再次感谢!
2赞 blues_driven 7/7/2015
我正在使用并在外部添加自定义验证器。$.validator.addMethod()$.validator.unobtrusive.adapters.add()
5赞 Adam 4/24/2012 #3

我不确定为什么这对我不起作用,但我选择使用您的代码并做一些稍微不同的事情。

在我的 JavaScript 加载中,我添加了以下内容,如果您选中该复选框并取消选中它,这将使该复选框触发非侵入性验证。此外,如果您提交表格。

$(function () {
        $(".checkboxonblurenabled").change(function () {
            $('form').validate().element(this);
        });
});

您还需要将 CSS 类添加到复选框中,如下所示。

@Html.CheckBoxFor(model => model.AgreeToPrivacyPolicy, new { @class = "checkboxonblurenabled"})

因此,我们现在需要连接模型并放入 out 类来处理服务器端验证(我从上面重用),但稍微改变了不显眼性。

下面是扩展 IClientValidate 的 customer 属性,如上例所示...

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

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        yield return new ModelClientValidationRule
        {
            ErrorMessage = this.ErrorMessage,
            ValidationType = "mustbetrue"
        };
    }
}

在模型中,对象属性设置所需的属性表示法

 [MustBeTrue(ErrorMessage = "Confirm you have read and agree to our privacy policy")]
    [Display(Name = "Privacy policy")]
    public bool AgreeToPrivacyPolicy { get; set; }

好了,我们准备加入 JavaScript。

(function ($) {
    /*
    START CHECK MUST BE TRUE - UNOBTRUSIVE JAVASCRIPT
    START CHECK MUST BE TRUE - UNOBTRUSIVE JAVASCRIPT
    START CHECK MUST BE TRUE - UNOBTRUSIVE JAVASCRIPT
    */
    jQuery.validator.unobtrusive.adapters.add("mustbetrue", ['maxint'], function (options) {
        options.rules["mustbetrue"] = options.params;
        options.messages["mustbetrue"] = options.message;
    });

    jQuery.validator.addMethod("mustbetrue", function (value, element, params) {

        if ($(element).is(':checked')) {
            return true;
        }
        else {
            return false;
        }
    });
    /*
    START CHECK MAX INT - UNOBTRUSIVE JAVASCRIPT
    START CHECK MAX INT - UNOBTRUSIVE JAVASCRIPT
    START CHECK MAX INT - UNOBTRUSIVE JAVASCRIPT
    */



} (jQuery));

是什么让它工作,是......井。在尝试执行上述建议的答案后查看 HTML 标记后,我的值全部设置为 true,但我选中的复选框为 false。因此,我决定让jQuery使用IsChecked来解决它

评论

0赞 amiry jd 4/24/2013
>>我不确定为什么这对我不起作用,我也:D但是您的解决方案是完整而完美的。真的谢谢你。好主意。+1 干杯。
2赞 Jesus Mogollon 12/18/2013 #4

对于那些这些解决方案都不起作用的人:

我正在使用 .Net Framework 4 和最新的 jquery 验证脚本文件来使用 Razor MVC 4。

在客户端和服务器端实现自定义属性验证后,它仍然不起作用。无论如何,我的表格正在发布。

所以这里有一个问题: JQuery 验证脚本的默认设置是忽略隐藏的标签,其中隐藏是 http://api.jquery.com/hidden-selector/,这通常不会成为问题,但我使用的 @Html.CheckBoxFor 样式是使用 CSS3 样式自定义的,该样式将显示更改为 none,并显示复选框的自定义图像,因此它永远不会在复选框上执行验证规则。

我的解决方法是在自定义客户端验证规则声明之前添加以下行:

$.validator.defaults.ignore = "";

它的作用是覆盖当前页面中所有验证的忽略设置,请注意,现在它也可以对隐藏字段执行验证(副作用)。

评论

0赞 Zac 7/10/2015
这简直要了我的命,直到我想起前端使用了一堆自定义 UI 元素,隐藏了我的输入。骇人听闻的解决方案是将输入放置在屏幕外,而不是隐藏它。
1赞 kavitha Reddy 2/26/2014 #5
<script>
    $(function () {
        $('#btnconfirm').click(function () {
            if ($("#chk").attr('checked') !== undefined ){
                return true;
            }
            else {

                alert("Please Select Checkbox ");
                return false;
            }
        });

    });
</script>
<div style="float: left">
                    <input type="checkbox" name="chk" id="chk"  />
                    I read and accept the terms and Conditions of registration
                </div>
  <input type="submit" value="Confirm"  id="btnconfirm" />
0赞 dhandapani harikrishnan 12/31/2014 #6
/// <summary> 
///  Summary : -CheckBox for or input type check required validation is not working the root cause and solution as follows
///
///  Problem :
///  The key to this problem lies in interpretation of jQuery validation 'required' rule. I digged a little and find a specific code inside a jquery.validate.unobtrusive.js file:
///  adapters.add("required", function (options) {
///  if (options.element.tagName.toUpperCase() !== "INPUT" || options.element.type.toUpperCase() !== "CHECKBOX") {
///    setValidationValues(options, "required", true);
///    }
///   });
///   
///  Fix: (Jquery script fix at page level added in to check box required area)
///  jQuery.validator.unobtrusive.adapters.add("brequired", 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;
///                       }
///  Fix : (C# Code for MVC validation)
///  You can see it inherits from common RequiredAttribute. Moreover it implements IClientValidateable. This is to make assure that rule will be propagated to client side (jQuery validation) as well.
///  
///  Annotation example :
///   [BooleanRequired]
///   public bool iAgree { get; set' }
///    

/// </summary>


public class BooleanRequired : RequiredAttribute, IClientValidatable
{

    public BooleanRequired()
    {
    }

    public override bool IsValid(object value)
    {
        return value != null && (bool)value == true;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        return new ModelClientValidationRule[] { new ModelClientValidationRule() { ValidationType = "brequired", ErrorMessage = this.ErrorMessage } };
    }
}

评论

0赞 dhandapani harikrishnan 12/31/2014
<script type=“text/jscript”> //自定义jQuery验证不显眼的脚本和适配器 jQuery.validator.unobtrusive.adapters.add(“brequired”, function (options) { //b-复选框必需 if (options.element.tagName.toUpperCase() == “INPUT” && options.element.type.toUpperCase() == “CHECKBOX”) { //setValidationValues(options, “required”, true); options.rules[“required”] = true; if (options.message) { options.messages[“required”] = options.message; } } });</脚本>