JQuery 使用一个错误验证多个字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1289086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JQuery Validate multiple fields with one error
提问by
How would I use the JQuery Validate plugin to have one error message for say 3 fields. For example 3 dob fields. By default I will get 3 error messages if all 3 fields are left blank. I only want one error linked to 3 fields. If any are blank the error comes up.
我将如何使用 JQuery Validate 插件为 3 个字段生成一条错误消息。例如 3 个 dob 字段。默认情况下,如果所有 3 个字段都留空,我将收到 3 条错误消息。我只想要一个链接到 3 个字段的错误。如果有任何空白,则会出现错误。
回答by Jules
Similar to Chris's
类似于克里斯的
$("form").validate({
rules: {
DayOfBirth: { required: true },
MonthOfBirth: { required: true },
YearOfBirth: { required: true }
},
groups: {
DateofBirth: "DayOfBirth MonthOfBirth YearOfBirth"
},
errorPlacement: function(error, element) {
if (element.attr("name") == "DayOfBirth" || element.attr("name") == "MonthOfBirth" || element.attr("name") == "YearOfBirth")
error.insertAfter("#YearOfBirth");
else
error.insertAfter(element);
}
});
回答by Chris
You can use the groups option to group together inputs. If each of the inputs has an error message, only one will be displayed.
您可以使用组选项将输入组合在一起。如果每个输入都有错误消息,则只会显示一个。
You'll probably want to override the messages associated with each of the fields, so they'll make more sense. For example, by default, you might get an error message like, "This Field is required." Well, that doesn't do the user alot of good when there are three inputs. You probably want to override the message to say "The Local Number is required." For this example, I just overrode all the error messages with "Please enter a valid Phone Number."
您可能希望覆盖与每个字段关联的消息,因此它们会更有意义。例如,默认情况下,您可能会收到一条错误消息,例如“此字段是必需的”。好吧,当有三个输入时,这对用户没有多大好处。您可能想要覆盖消息以说“需要本地号码”。对于这个例子,我只是用“请输入一个有效的电话号码”覆盖了所有的错误消息。
<input type="text" name="countryCode" />
<input type="text" name="areaCode" />
<input type="text" name="localNumber" />
groups: {
phoneNumber: "countryCode areaCode localNumber"
},
rules: {
'countryCode': {
required: true,
minlength:3,
maxlength:3,
number:true
},
'contactInformation[areaCode]': {
required: true,
minlength:3,
maxlength:3,
number:true
},
'contactInformation[localNumber]': {
required: true,
minlength:4,
maxlength:4,
number:true
},
},
messages: {
"countryCode": {
required: "Please enter a valid Phone Number",
minlength: "Please enter a valid Phone Number",
maxlength: "Please enter a valid Phone Number",
number: "Please enter a valid Phone Number"
},
"areaCode": {
required: "Please enter a valid Phone Number",
minlength: "Please enter a valid Phone Number",
maxlength: "Please enter a valid Phone Number",
number: "Please enter a valid Phone Number"
},
"localNumber": {
required: "Please enter a valid Phone Number",
minlength: "Please enter a valid Phone Number",
maxlength: "Please enter a valid Phone Number",
number: "Please enter a valid Phone Number"
}
},
回答by Naoise Golden
I thought I should share this. The full code that worked for me.
我想我应该分享这个。对我有用的完整代码。
HTML
HTML
<div class="clearfix bl">
<label>Fecha de nacimiento</label>
<select name="fechanacimdia" id="fechanacimdia"></select>
<select name="fechanacimmes" id="fechanacimmes"></select>
<select name="fechanacimano" id="fechanacimano"></select>
</div>
JS
JS
//hay que poblar selects de fecha
dia = $('#fechanacimdia');
mes = $('#fechanacimmes');
ano = $('#fechanacimano');
dia.append('<option>Día</option>');
for(i=1;i<=31;i++) {
dia.append('<option value="'+i+'">'+i+'</option>');
}
meses = ["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"]
mes.append('<option>Mes</option>');
for(i=1;i<=12;i++) {
mes.append('<option value="'+i+'">'+meses[i-1]+'</option>');
}
d = new Date();
year = d.getFullYear();
maxage = 100;
minage = 16;
ano.append('<option>A?o</option>');
for(i=year-minage;i>=year-maxage;i--) {
ano.append('<option value="'+i+'">'+i+'</option>');
}
//--------- validate ------------------------
$('#formulario').validate({
rules: {
fechanacimdia: { required: true },
fechanacimmes: { required: true },
fechanacimano: { required: true, validdate: true }
},
groups: {
fechanacim: "fechanacimdia fechanacimmes fechanacimano"
},
messages: {
fechanacimdia: "Fecha de nacimiento no es válida.",
fechanacimmes: "Fecha de nacimiento no es válida.",
fechanacimano: "Fecha de nacimiento no es válida."
},
});
//funcion auxiliar para validar fecha de nacimiento correcta
jQuery.validator.addMethod("validdate", function(value, element) {
var month = +$('#fechanacimmes').val() - 1; // Convert to numbers with "+" prefix
var day = +$('#fechanacimdia').val();
var year = +$('#fechanacimano').val();
var date = new Date(year, month, day); // Use the proper constructor
return date.getFullYear() == year && date.getMonth() == month && date.getDate() == day;
});
回答by inadcod
this is for the HTML part:
这是针对 HTML 部分的:
<div>
<p class="myLabel left">Date of birth:</p>
<p class="mandatory left">*</p>
<div class="left">
<p><input type="text" name="dobDay" class="required" /></p>
<p><i>dd</i></p>
</div>
<div class="left">
<p><input type="text" name="dobMonth" class="required" /></p>
<p><i>mm</i></p>
</div>
<div class="left">
<p><input type="text" name="dobYear" class="required" /></p>
<p><i>yyyy</i></p>
</div>
<div class="clear"></div>
<div class="myError">
<label for="dateOfBirth" class="error">Please enter a valid date.</label>
</div>
</div>
This is the script i used:
这是我使用的脚本:
$(document).ready(function() {
$("#myForm").validate({
groups: {
dateOfBirth: "dobDay dobMonth dobYear"
},
rules: {
'dobDay': {
required: true,
minlength:1,
maxlength:2,
range: [1, 31],
number:true
},
'dobMonth': {
required: true,
minlength:1,
maxlength:2,
range: [1, 12],
number:true
},
'dobYear': {
required: true,
minlength:4,
maxlength:4,
number:true
},
},
});
});
all the HTML part can be customize as you see fit. I used these complex layout because I needed to add this field to an already existing form. But it is an example that works! Hope it helps anyone!
所有 HTML 部分都可以根据您的需要进行自定义。我使用这些复杂的布局是因为我需要将此字段添加到现有表单中。但这是一个有效的例子!希望它可以帮助任何人!
回答by matsondawson
My take on it was to change jQuery validator
to validate anything with the validateable
attribute on it as well as the standard inputs. You can get the 1.9.0
modified version of the plugin here
我对它的看法是更改jQuery validator
以验证带有validateable
属性的任何内容以及标准输入。您可以1.9.0
在此处获取插件的修改版本
Basically you import the new jquery validator and do something like this:
基本上,您导入新的 jquery 验证器并执行以下操作:
<script>
$.validator.addMethod(
"groupnotnull",
function(value, element) {
return $("input[type='text']:filled",element).length!=0;
},
function(regexp, element) {
return "At least one input must be specified";
}
);
</script>
<div validateable="true" name="groupValidated" groupnotnull="true">
<input type="text" name="foo"/>
<input type="text" name="blah"/>
</div>
The modifications required on jQuery validator
were to make it use .attr('name')
instead of .name
because .name
only works on form fields. And modify the key up handlers etc. to bind to children of the validateable
element.
所需的修改jQuery validator
是使其使用.attr('name')
而不是.name
因为.name
仅适用于表单字段。并修改 key up 处理程序等以绑定到validateable
元素的子元素。
This is a little more dynamic than groups in that it allows fields to be validated in relation to each other rather than just as single entities.
这比组更具动态性,因为它允许字段相互关联而不仅仅是作为单个实体进行验证。
回答by sweets-BlingBling
This code will display one common error if any of the required fields is blank.
如果任何必填字段为空,此代码将显示一个常见错误。
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
$("#myform").validate({
invalidHandler: function(form, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
var message ='You missed ' + errors + ' fields.';
$("#messageBox").html(message);
$("#messageBox").show();
} else {
$("#messageBox").hide();
}
},
showErrors: function(errorMap, errorList) {
},
submitHandler: function() { alert("Submit!") }
})
});
</script>
</head>
<body>
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
<div id="messageBox"></div>
<ul id="errorlist"></ul>
<form id="myform" action="/loginurl" method="post">
<label>DOB1</label>
<input name="dob1" class="required" />
<label>DOB2</label>
<input name="dob2" class="required" />
<label>DOB3</label>
<input name="dob3" class="required" />
<br/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
回答by Jarrett Meyer
A couple options: Check out the errorContainer
. You can make all of the errors go to a completely separate <div>
. Or you can check out the invalid
block, and just have an errorMessage.show()
command.
几个选项:查看errorContainer
. 您可以将所有错误归为一个完全独立的<div>
. 或者,您可以查看该invalid
块,然后只需一个errorMessage.show()
命令。