0

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

它是先给消息 for Descriptionthen for Codethen for Name。但我希望验证应该首先为Name然后CodeDescription

$(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:

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

如何解决这个问题?

4

1 回答 1

0

jQuery 验证插件按 DOM的顺序检索元素(参见$.validator.prototype.elements函数,l. 461)。

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

$.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
    );
}
于 2012-12-08T21:54:31.727 回答