Javascript 验证动态添加的输入字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11536271/
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
Validate Dynamically Added Input fields
提问by Rav
I have used thisjquery validation plugin for the following form.
我已将这个jquery 验证插件用于以下表单。
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#commentForm").validate();
});
function addInput() {
var obj = document.getElementById("list").cloneNode(true);
document.getElementById('parent').appendChild(obj);
}
</script>
<form id="commentForm" method="get" action="">
<p id="parent">
<input id="list" class="required" />
</p>
<input class="submit" type="submit" value="Submit"/>
<input type="button" value="add" onClick="addInput()" />
</form>
When the add button is clicked a new input is dynamically added. However when the form is submitted only the first input field is validated. How can i validate dynamically added inputs? Thank you...
单击添加按钮时,会动态添加新输入。但是,当提交表单时,仅验证第一个输入字段。如何验证动态添加的输入?谢谢...
回答by Angel
You should have 'name' attribute for your inputs. You need to add the rules dynamically, one option is to add them when the form submits.
您的输入应该具有“名称”属性。您需要动态添加规则,一种选择是在表单提交时添加它们。
And here is my solution that I've tested and it works:
这是我测试过的解决方案,它有效:
<script type="text/javascript">
$(document).ready(function() {
var numberIncr = 1; // used to increment the name for the inputs
function addInput() {
$('#inputs').append($('<input class="comment" name="name'+numberIncr+'" />'));
numberIncr++;
}
$('form.commentForm').on('submit', function(event) {
// adding rules for inputs with class 'comment'
$('input.comment').each(function() {
$(this).rules("add",
{
required: true
})
});
// prevent default submit action
event.preventDefault();
// test if form is valid
if($('form.commentForm').validate().form()) {
console.log("validates");
} else {
console.log("does not validate");
}
})
// set handler for addInput button click
$("#addInput").on('click', addInput);
// initialize the validator
$('form.commentForm').validate();
});
</script>
And the html form part:
和 html 表单部分:
<form class="commentForm" method="get" action="">
<div>
<p id="inputs">
<input class="comment" name="name0" />
</p>
<input class="submit" type="submit" value="Submit" />
<input type="button" value="add" id="addInput" />
</div>
</form>
Good luck! Please approve answer if it suits you!
祝你好运!如果答案适合您,请批准!
回答by RitchieD
Reset form validation after adding new fields.
添加新字段后重置表单验证。
function resetFormValidator(formId) {
$(formId).removeData('validator');
$(formId).removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse(formId);
}
回答by Albert
The one mahesh posted is not working because the attribute name is missing:
发布的一个 mahesh 不起作用,因为缺少属性名称:
So instead of
所以代替
<input id="list" class="required" />
You can use:
您可以使用:
<input id="list" name="list" class="required" />
回答by Yogesh Maurya
You need to re-parse the form after adding dynamic content in order to validate the content
添加动态内容后需要重新解析表单以验证内容
$('form').data('validator', null);
$.validator.unobtrusive.parse($('form'));
回答by Shiva Manhar
jquery validation plugin version work fine v1.15.0but v1.17.0not work for me.
jquery 验证插件版本工作正常v1.15.0但v1.17.0不适合我。
$(document).find('#add_patient_form').validate({
ignore: [],
rules:{
'email[]':
{
required:true,
},
},
messages:{
'email[]':
{
'required':'Required'
},
},
});
回答by Zia
$('#form-btn').click(function () {
//set global rules & messages array to use in validator
var rules = {};
var messages = {};
//get input, select, textarea of form
$('#formId').find('input, select, textarea').each(function () {
var name = $(this).attr('name');
rules[name] = {};
messages[name] = {};
rules[name] = {required: true}; // set required true against every name
//apply more rules, you can also apply custom rules & messages
if (name === "email") {
rules[name].email = true;
//messages[name].email = "Please provide valid email";
}
else if(name==='url'){
rules[name].required = false; // url filed is not required
//add other rules & messages
}
});
//submit form and use above created global rules & messages array
$('#formId').submit(function (e) {
e.preventDefault();
}).validate({
rules: rules,
messages: messages,
submitHandler: function (form) {
console.log("validation success");
}
});
});
回答by JoshdeVries
In regards to @RitchieD response, here is a jQuery plugin version to make things easier if you are using jQuery.
关于@RitchieD 的回应,这里有一个 jQuery 插件版本,如果您使用 jQuery,它会让事情变得更容易。
(function ($) {
$.fn.initValidation = function () {
$(this).removeData("validator");
$(this).removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse(this);
return this;
};
}(jQuery));
This can be used like this:
这可以像这样使用:
$("#SomeForm").initValidation();
回答by sstauross
In case you have a form you can add a class name as such:
如果你有一个表单,你可以添加一个类名:
<form id="my-form">
<input class="js-input" type="text" name="samplename" />
<input class="js-input" type="text" name="samplename" />
<input class="submit" type="submit" value="Submit" />
</form>
you can then use the addClassRulesmethod of validator to add your rules like this and this will apply to all the dynamically added inputs:
然后,您可以使用验证器的addClassRules方法来添加这样的规则,这将适用于所有动态添加的输入:
$(document).ready(function() {
$.validator.addClassRules('js-input', {
required: true,
});
//validate the form
$('#my-form').validate();
});
回答by Bhavika Patel
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#commentForm").validate();
});
function addInput() {
var indexVal = $("#index").val();
var index = parseInt(indexVal) + 1
var obj = '<input id="list'+index+'" name=list['+index+'] class="required" />'
$("#parent").append(obj);
$("#list"+index).rules("add", "required");
$("#index").val(index)
}
</script>
<form id="commentForm" method="get" action="">
<input type="hidden" name="index" name="list[1]" id="index" value="1">
<p id="parent">
<input id="list1" class="required" />
</p>
<input class="submit" type="submit" value="Submit"/>
<input type="button" value="add" onClick="addInput()" />
</form>
回答by leonardeveloper
Try using input arrays:
尝试使用输入数组:
<form action="try.php" method="post">
<div id="events_wrapper">
<div id="sub_events">
<input type="text" name="firstname[]" />
</div>
</div>
<input type="button" id="add_another_event" name="add_another_event" value="Add Another" />
<input type="submit" name="submit" value="submit" />
</form>
and add this script and jQuery, using foreach() to retrieve the data being $_POST'ed:
并添加此脚本和jQuery,使用 foreach() 检索被 $_POST'ed 的数据:
<script>
$(document).ready(function(){
$("#add_another_event").click(function(){
var $address = $('#sub_events');
var num = $('.clonedAddress').length; // there are 5 children inside each address so the prevCloned address * 5 + original
var newNum = num + 1;
var newElem = $address.clone().attr('id', 'address' + newNum).addClass('clonedAddress');
//set all div id's and the input id's
newElem.children('div').each (function (i) {
this.id = 'input' + (newNum*5 + i);
});
newElem.find('input').each (function () {
this.id = this.id + newNum;
this.name = this.name + newNum;
});
if (num > 0) {
$('.clonedAddress:last').after(newElem);
} else {
$address.after(newElem);
}
$('#btnDel').removeAttr('disabled');
});
$("#remove").click(function(){
});
});
</script>