如何使用不引人注目的jQuery验证手动重新验证/触发验证? [英] How to manually revalidate / trigger validation using unobtrusive jQuery validation?

查看:71
本文介绍了如何使用不引人注目的jQuery验证手动重新验证/触发验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了自己的条件验证属性,以通过继承RequiredAttribute并实现IClientValidatable来在客户端和服务器上验证我的MVC模型.这个想法是,如果我模型上的布尔属性为true,则需要另一个属性.在视图中,这本身显示为一个复选框,指示是否需要填写文本框.

I have created my own conditional validation attribute to validate my MVC model on both the client and the server by inheriting from RequiredAttribute and implementing IClientValidatable. The idea is that if a boolean property on my model is true, then another property is required. In the view this manifests itself as a checkbox which dictates whether a textbox needs to be filled in.

这非常完美,除了用户执行以下操作时:

This works perfect except for when the user performs the following actions:

  • 选中复选框(此字段为必填字段).
  • 提交表单(客户端验证运行,显示错误消息).
  • 用户取消选中复选框(错误消息仍然存在,不再需要该字段).

当复选框处于选中状态或未选中状态时,我想重新验证表单,或者更好的方法是重新验证该字段,以便不再显示错误消息.我已经尝试了各种调用jQuery validate()方法的组合,但是似乎没有什么可以重新运行验证.

I would like to revalidate the form when the checkbox is checked or unchecked, or even better just revalidate that field, so that the error message is no longer displayed. I have tried various combinations of calling the jQuery validate() method, but nothing seems to be able to re-run validation.

我使用以下javascript设置我的验证功能和关联的不干扰适配器.

I use the following javascript to set up my validation function and the associated unobtrusive adapter.

$.validator.addMethod(
    "requiredif",
    function(value, element, parameters) {
        var selector = "#" + parameters["dependentpropertyname"];
        var triggerValue = parameters["triggervalue"].toString().toLowerCase();
        var actualValue = $(selector).is(":checked").toString().toLowerCase();
        if (actualValue === triggerValue) return $.validator.methods.required.call(this, value, element, parameters);

        return true;
    });

$.validator.unobtrusive.adapters.add(
    "requiredif",
    ["dependentpropertyname", "triggervalue"],
    function(options) {
        options.rules["requiredif"] = {
            dependentpropertyname: options.params["dependentpropertyname"],
            triggervalue: options.params["triggervalue"]
        };
        options.messages["requiredif"] = options.message;
    }
);

谢谢!

推荐答案

我有一个类似的问题,我想使用jquery validate和jquery ui重新验证datepicker字段. 这篇文章帮助我弄清楚了.

I had a similar problem where I wanted to revalidate a datepicker field using jquery validate and jquery ui. This post helped me figure it out.

关键在于,只需将回调添加到该选择器的有效方法即可.像这样:

The key, is just add a callback to the valid method for that selector. Something like:

$(".requiredif").change(function() {
  $(this).valid();
})

这篇关于如何使用不引人注目的jQuery验证手动重新验证/触发验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆