首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >显示从最后一个元素到第一个元素的错误

显示从最后一个元素到第一个元素的错误
EN

Stack Overflow用户
提问于 2012-12-07 21:07:18
回答 1查看 140关注 0票数 0

在验证表单时,它工作正常,但是

它首先为Description提供消息,然后为Code提供消息,然后为Name提供消息。但我希望验证应该首先针对Name,然后针对Code,然后针对Description

代码语言:javascript
复制
$(document).ready(function() {
    $("#added").validate({
        rules: {
            Name: {
                required: true
            },
            Code: {
                required: true
            },
            Description: {
                required: true
            },

        },

        messages: {
            Name: {
                required: "Enter Name"
            },
            Code: {
                required: "Enter code"
            },

            Description: {
                required: "Enter Description"
            },
        },

        errorPlacement: function(error, element) {
            $("#error-messages").html(error); // error container
        }
    });​
});

HTML:

代码语言:javascript
复制
<div id="error-messages"></div>
<s:form action="added" id="added" method="post" >
   <s:textfield name="Name" id="Name" label="Name" labelposition="top" />
   <s:textarea name="Code" id="Code" rows="10" cols="50" 
                 label="Code" labelposition="top"/>

   <s:textarea name="Description" id="Description" rows="5" cols="50"
                 label="Description" labelposition="top"/>
<s:form>

如何解决这个问题?

EN

回答 1

Stack Overflow用户

发布于 2012-12-09 05:54:32

jQuery validation plugin按照DOM的顺序检索元素(参见$.validator.prototype.elements函数,1.461)。

因此,为了从最后一个元素到第一个元素进行验证,一个解决方案是在我们自己的脚本部分中使用以下代码修补此函数:

代码语言:javascript
复制
$.validator.prototype.elements = function() {
    var validator = this,
        rulesCache = {};

    // select all valid inputs inside the form (no submit or reset buttons)
    return 
        $(  // Added this in order to re-encapsulate in a jQuery object the reversed array (see below)
        $(this.currentForm)
        .find("input, select, textarea")
        .not(":submit, :reset, :image, [disabled]")
        .not( this.settings.ignore )
        .filter(function() {
            if ( !this.name && validator.settings.debug && window.console ) {
                console.error( "%o has no name assigned", this);
            }

            // select only the first element for each name, and only those with rules specified
            if ( this.name in rulesCache || !validator.objectLength($(this).rules()) ) {
                return false;
            }

            rulesCache[this.name] = true;
            return true;
        })
        .get().reverse()  // Added this in order to reverse the array order
    );
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13763710

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档