jQuery 验证插件不验证动态创建的表单元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18022224/
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 Validation plugin doesn't validate dynamically created form elements
提问by VitaminCpp
I've a form where you dynamically can add new rows with input elements. Before submitting my form it gets validated by using the plugin from here http://jqueryvalidation.org/. Currently the code for adding a new row with input elements looks like this:
我有一个表单,您可以在其中动态添加带有输入元素的新行。在提交我的表单之前,它通过使用来自http://jqueryvalidation.org/的插件进行验证。目前,用于添加带有输入元素的新行的代码如下所示:
function addTimeRow(table, stime)
{
//var rowIdx = $('#seminarTimes tr').length - 1;
var $id = $('<input type="hidden" name="stid[]">');
var $dateField = $('<input type="text" name="date[]" class="input-mini">');
var $date = $('<div class="input-append date">')
.append($dateField)
.append('<span class="add-on"><i class="icon-calendar">');
var $from = $('<input type="text" name="from[]" class="input-mini"> <span>(hh:mm)</span>');
var $to = $('<input type="text" name="to[]" class="input-mini"> <span>(hh:mm)</span>');
if (typeof(stime) !== 'undefined')
{
$id.attr('value', stime.id);
$dateField.attr('value', stime.date);
$from.attr('value', stime.from);
$to.attr('value', stime.to);
}
else
$id.attr('value', -1);
// Attach new input row.
table
.append($('<tr>')
.append($id)
.append($('<td>')
.append($date))
.append($('<td>')
.append($from))
.append($('<td>')
.append($to))
.append($('<td class="vert">')
.append($('<button class="btn btn-mini btnDelTime"><i class="icon-trash">'))));
// Attach rules.
$dateField.rules('add', { required: true });
$from.rules('add', { required: true });
$to.rules('add', { required: true });
// Create pickers.
$date.datepicker({
language: 'de',
autoclose: true,
todayBtn: true,
todayHighlight: true,
}).on('changeDate', function(e) {
editSeminarFormValidator.element($dateField);
$date.datepicker('hide');
});
}
In my document ready event I initialize the JQuery validation plugin like so:
在我的文档就绪事件中,我像这样初始化 JQuery 验证插件:
var validator = $('#editSeminarForm').validate({
debug: true,
errorLabelContainer: '#error-label',
wrapper: 'li',
messages: {
price: 'Bitte geben Sie einen Preis ein!'
}
});
Now my actual problem is, that none of the new input fields gets validated. I know that I'm using input arrays for easier handling the form on the server-side. Are these arrays the problem why my input fields don't get validated?
现在我的实际问题是,没有一个新的输入字段得到验证。我知道我使用输入数组是为了更轻松地处理服务器端的表单。这些数组是为什么我的输入字段没有得到验证的问题吗?
EDIT - My current solution:
编辑 - 我目前的解决方案:
var rowIdx = 0;
function addTimeRow(table, stime)
{
var $id = $($.validator.format('<input type="hidden" id="stid{0}" name="stid[{0}]">', rowIdx));
var $dateField = $($.validator.format('<input type="text" id="date{0}" name="date[{0}]" class="input-mini">', rowIdx));
var $date = $('<div class="input-append date">')
.append($dateField)
.append('<span class="add-on"><i class="icon-calendar">');
var $from = $($.validator.format('<input type="text" id="from{0}" name="from[{0}]" class="input-mini"> <span>(hh:mm)</span>', rowIdx));
var $to = $($.validator.format('<input type="text" id="to{0}" name="to[{0}]" class="input-mini"> <span>(hh:mm)</span>', rowIdx));
if (typeof(stime) !== 'undefined')
{
$id.attr('value', stime.id);
$dateField.attr('value', stime.date);
$from.attr('value', stime.from);
$to.attr('value', stime.to);
}
else
$id.attr('value', -1);
// Attach new input row.
table
.append($('<tr>')
.append($id)
.append($('<td>')
.append($date))
.append($('<td>')
.append($from))
.append($('<td>')
.append($to))
.append($('<td class="vert">')
.append($('<button class="btn btn-mini btnDelTime"><i class="icon-trash">'))));
// Attach rules.
$dateField.rules('add', { required: true });
$from.rules('add', { required: true });
$to.rules('add', { required: true });
// Create pickers.
$date.datepicker({
language: 'de',
autoclose: true,
todayBtn: true,
todayHighlight: true,
}).on('changeDate', function(e) {
editSeminarFormValidator.element($dateField);
$date.datepicker('hide');
});
rowIdx++;
}
Works like a charm!
奇迹般有效!
回答by Sparky
There seems to be nothing majorly wrong with the logic you're using for adding rules to the new elements. Although, you'll need to attach the .rules()method to a jQuery objectusing a jQuery selector, not the element's HTML.
您用于向新元素添加规则的逻辑似乎没有什么大问题。 虽然,您需要使用 jQuery选择器将.rules()方法附加到 jQuery对象,而不是元素的 HTML。
something like...
就像是...
$('#myInputID').rules('add', {...});
or...
或者...
$('input[name="myname"]').rules('add', {...});
But the heart of your problem is in here...
但是你的问题的核心在这里......
var $id = $('<input type="hidden" name="stid[]">');
var $dateField = $('<input type="text" name="date[]" class="input-mini">');
var $date = $('<div class="input-append date">')
.append($dateField)
.append('<span class="add-on"><i class="icon-calendar">');
var $from = $('<input type="text" name="from[]" class="input-mini"> <span>(hh:mm)</span>');
var $to = $('<input type="text" name="to[]" class="input-mini"> <span>(hh:mm)</span>');
Notice the nameattribute? It's going to be the same for every new row.
注意name属性?每一个新行都是一样的。
The problem is that the jQuery Validate plugin will not work unless each inputelement contains a uniquename. Simply modify your code to ensure that a new nameis created for each new element.
问题是 jQuery Validate 插件将无法工作,除非每个input元素都包含一个唯一的name. 只需修改您的代码以确保name为每个新元素创建一个新元素。
EDIT: Indexed arrays will work fine with this plugin. Just increment the index when you create the new element.
编辑:索引数组可以很好地与这个插件一起工作。创建新元素时只需增加索引。
name="from[0]", name="from[1]", name="from[2]", etc.
name="from[0]",name="from[1]",name="from[2]",等。
回答by Ionu? Staicu
It might be a duplicate of:
它可能是以下内容的副本:
- Adding jQuery validator rules to dynamically created elements in ASP
- jQuery - How to dynamically add a validation rule
Long story short, you have to call
长话短说,你必须打电话
$('input').rules('add', 'required')
http://validation.bassistance.de/rules
http://validation.bassistance.de/rules
or, updated,
或者,更新,
http://jqueryvalidation.org/rules
http://jqueryvalidation.org/rules
As a side note: since you inject a lot of HTMLfrom JSit might be a good idea to try a template engine.
附带说明:由于您HTML从中注入了很多,JS因此尝试模板引擎可能是个好主意。

