我如何只显示所有必填字段的一条消息?
例如 - 我有3个字段,所有字段都是必需的。 jquery.validate显示每个字段的错误,但我只想显示一条消息,例如"所有标记的字段都是必需的"。
我无法使用汇总值(例如numberOfInvalids左右),因为在同一时间我需要显示拼写错误(错误的电子邮件,短密码等)。
代码示例(左侧表单是验证,右侧是显示它应该是什么样子): screenshot of 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"
});
提前致谢!
答案 0 :(得分:0)
指定错误消息的分组 。组由一个任意组名作为键,空格分隔的元素名列表作为值。
$('.form-validate').validate({
// your other options,
groups: {
mygroup: "q w e"
}
});
如果您的字段名称是动态生成的,那么在调用groups
之前,您需要动态构建.validate()
选项。 Here is an example
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
},
....
DEMO 2:jsfiddle.net/8gxprw4y/3/
答案 1 :(得分:-1)
首先,您必须包含JQuery cdn&#39;
<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.");
}
}); }