jquery validate - 检查哪个规则未满足

发布于 2024-12-08 05:22:27 字数 333 浏览 3 评论 0原文

我有一个包含多个字段并使用 jQuery 验证插件的表单。我的输入有几个规则:

{
    required : "#somecheckbox:not(:checked)",
    regex : "\d{10}",
    maxlength : 10,
    remote : [object Object],
    __dummy__ : true
} 

我想知道的是,如何检查哪些规则未得到满足(或者某些特定规则是否有效)。我知道这是可能的,因为远程验证不会触发 ajax 请求,直到其他请求已满,但我无法在 jquery.validate.js 中找到它是如何完成的。

I have a form with several fields and using jQuery validation plugin. My input has several rules:

{
    required : "#somecheckbox:not(:checked)",
    regex : "\d{10}",
    maxlength : 10,
    remote : [object Object],
    __dummy__ : true
} 

What I want to know is, how I can check which of these rules are not fulfilled (or is some specific rule valid or not). I know that this is possible as remote validation does not fire ajax requests until others are fullfiled, but I cannot find in jquery.validate.js how it is done.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

执妄 2024-12-15 05:22:27

我已经通过检查 jQuery 验证插件的源代码弄清楚了如何做到这一点,所以我制作了自己的函数来利用它:

$.validator.prototype.ruleValidationStatus = function( element ) {
    element = $(element)[0];
    var rules = $(element).rules();
    var errors ={};
    for (var method in rules ) {
        var rule = { method: method, parameters: rules[method] };
        try {
            var result = $.validator.methods[method].call( this, element.value.replace(/\r/g, ""), element, rule.parameters );

            errors[rule.method] = result ;

        } catch(e) {
            console.log(e);
        }
    }
    return errors;
} 

用法很简单:

$("#myform").validate().ruleValidationStatus($("#myField"))

示例结果是:

{
    required : true,
    regex : true,
    maxlength : true,
    remote : false,
    __dummy__ : true
} 

从这个对象很容易看出哪些规则不满足。

I have figured out how to do this by examining source of jQuery validate plugin, so I made my own function to tap into it:

$.validator.prototype.ruleValidationStatus = function( element ) {
    element = $(element)[0];
    var rules = $(element).rules();
    var errors ={};
    for (var method in rules ) {
        var rule = { method: method, parameters: rules[method] };
        try {
            var result = $.validator.methods[method].call( this, element.value.replace(/\r/g, ""), element, rule.parameters );

            errors[rule.method] = result ;

        } catch(e) {
            console.log(e);
        }
    }
    return errors;
} 

Usage is simple:

$("#myform").validate().ruleValidationStatus($("#myField"))

And sample result is:

{
    required : true,
    regex : true,
    maxlength : true,
    remote : false,
    __dummy__ : true
} 

From this object it is easy to see what rules are not satisfied.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文