开发者

jQuery Validate Plugin groups: Error message shows for last invalid field instead of first invalid field in the group

When using groups in the jQuery validate plugin, for some reason it always shows the error message for the last field in the group if both fields are invalid. Ideally it should show the error message for the first field in the group that's invalid.

Here's the code:

<form id="form1">
    <div>
        <label>Name</label>
        <input type="text" name="firstName" id="firstName" />
        <input type="text" name="lastName" id="lastName" />
    </div>
    <div>
        <input type="submit" value="Test" />
    </div>
</form>

And the JS:

$(function() {
    $('#form1').validate({
        messages: {
            firstName: {
                required: 'first name is required'
            },
            lastName: {
                required: 'last name is required'
            }
        },
        rules: {
            firstName: {
                required: true
            },
            lastName: {
                required: true
            }
        },
        groups: {
            fullName: 'firstName lastName'
        }
    });
});

Ideally, when clicking on the submit button I'd like the following scenarios to play out:

  1. Both fields are empty: "first name is required"
  2. First name filled in, last name empty: "last name is required"
  3. Last name filled in, first name empty: "first name is required"

Anyone know how to accomplish this?

One other item I'm also struggling with is if I use the "success" function to show a "valid" label when the user completes each field, it seems to ignore the fact that the fields are in groups. I'd like to only show the "valid" message when BOTH fields in the group are valid.

If anyone could help with either o开发者_运维知识库f these issues that would be great.

Thanks!


Try this

$(function() {
    $('#form1').validate({
        messages: {
            firstName: {
                required: 'first name is required'
            },
            lastName: {
                required: 'last name is required'
            }
        },
        rules: {
            firstName: {
                required: true,
                lastName: {
                    required: true
                }
            }
        },
        groups: {
            fullName: 'firstName lastName'
        }
    });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜