我正在从事一个项目,我需要在该项目中验证一个动态插入DOM的表单。想知道如何正确实现这一目标?
我尝试以下未能成功:
$(document).on('formValidation', '#myform', {
fields: {
"first_name": {
validators: {
当前验证格式:
$('#myForm')
.formValidation({
fields: {
"first_name": {
validators: {
notEmpty: {
message: 'Please enter a first name.'
}
}
},
一种解决方案是使用MutationObserver在节点上聆听到DOM。
。当将具有ID myForm
的表单添加到身体中时,您将知道,然后可以执行您的表单验证逻辑。
例如
// dynamically add the form for testing
setTimeout(function(){
var elem = document.createElement('form');
elem.id="myForm";
elem.innerHTML="Hello I am a dynamically added form";
document.body.appendChild(elem);
}, 2000);
// select the target node
var target = document.body;
// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
mutation.addedNodes.forEach(function(node){
if(node.id === "myForm"){
console.log("myForm was just added");
// do validation logic here
}
})
});
});
// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };
// pass in the target node, as well as the observer options
observer.observe(target, config);