我如何为所有必填字段只显示一条消息?
例如 - 我有 3 个字段,所有这些都是必需的。 jquery.validate 为每个字段显示错误,但我只想显示一条消息,例如"所有标记的字段都是必填的"。
我不能使用摘要值(如 numberOfInvalids 左右(,因为同时我需要显示拼写错误(错误的电子邮件、短密码等(。
代码示例(左边的表单是验证,右边的表单是显示它应该是什么样子(: codepen.io 截图
https://codepen.io/mike-polo/pen/WyZRBd
.HTML:
<form class="form-validate">
<div class="form-errors">
<h3>Errors:</h3>
<ul></ul>
</div>
<h3>All fields required:</h3>
<div class="form-field">
<input type="text" name="q" id="f-q" placeholder="Required text field" required>
</div>
<div class="form-field">
<input type="email" name="w" id="f-w" placeholder="Required email field" required>
</div>
<div class="form-field">
<input type="text" name="e" id="f-e" placeholder="Required text field" required>
</div>
<input type="submit">
</form>
.JS:
$(document).ready(function(){
$('.form-validate').validate({
errorContainer: $(this).find('.form-errors'),
errorLabelContainer: $('ul', $(this).find('.form-errors')),
wrapper: 'li',
});
});
$.extend($.validator.messages, {
required: "Fill all marked fields please"
});
提前谢谢!
只需使用groups
选项:
指定错误消息的分组 。组由作为键的任意组名和作为值的以空格分隔的元素名称列表组成。
$('.form-validate').validate({
// your other options,
groups: {
mygroup: "q w e"
}
});
演示:jsfiddle.net/8gxprw4y/
如果字段名称是动态生成的,则需要在调用.validate()
之前动态构造groups
选项。 下面是一个示例。
var names = ""; // create empty string
$('[id^="f-"]').each(function() { // grab each input starting w/ the class
names += $(this).attr('name') + " "; // append each name + single space to string
});
names = $.trim(names); // remove the empty space from the end
$('.form-validate').validate({
// your other options,
groups: {
myGroup: names // reference the string
},
....
演示 2:jsfiddle.net/8gxprw4y/3/
首先,您必须包含 JQuery cdn 的
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
和
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
然后更改您的代码 试试这个
<form class="form-validate" id="myForm" method="post" action="">
<div class="form-errors">
<h3>Errors:</h3>
<span id="errorMSG"> </span>
</div>
<h3>All fields required:</h3>
<div class="form-field">
<input type="text" name="q" id="f-q" required placeholder="Required text field" >
</div>
<div class="form-field">
<input type="email" name="w" id="f-w" required placeholder="Required email field" >
</div>
<div class="form-field">
<input type="text" name="e" id="f-e" required placeholder="Required text field" >
</div>
<input type="submit" onclick="checkSubmission();">
和JQuery
function checkSubmission(){$("#myForm").validate({
rules:
{
q:
{
required: true,
},
w:
{
required:true,
},
e:
{
required:true,
}
},
showErrors: function(errorMap, errorList) {
$(".form-errors").html("All fields must be completed before you submit the form.");
}
}); }