jQuery 验证插件组:显示组中最后一个无效字段而不是第一个无效字段的错误消息
在 jQuery 验证插件中使用组时,由于某种原因,如果两个字段都无效,它总是显示组中最后一个字段的错误消息。理想情况下,它应该显示组中第一个无效字段的错误消息。
代码如下:
<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>
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'
}
});
});
理想情况下,当单击提交按钮时,我希望出现以下场景:
- 两个字段均为空:“名字为必填”
- 名字已填写,姓氏为空:“姓氏是必需的”
- 姓氏已填写,名字为空:“名字是必需的”
有人知道如何完成此操作吗?
我也在努力解决的另一件事是,如果我使用“成功”功能在用户完成每个字段时显示“有效”标签,它似乎忽略了字段分组的事实。我只想在组中的两个字段都有效时才显示“有效”消息。
如果有人可以帮助解决这两个问题,那就太好了。
谢谢!
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:
- Both fields are empty: "first name is required"
- First name filled in, last name empty: "last name is required"
- 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 of these issues that would be great.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
试试这个
Try this