0

我正在开发一个需要验证动态插入到 DOM 的表单的项目。想知道如何正确地做到这一点?

我尝试了以下失败:

  $(document).on('formValidation', '#myform', {
                fields: {
                    "first_name": {
                        validators: {

当前验证格式:

$('#myForm')
        .formValidation({
            fields: {
                "first_name": {
                    validators: {
                        notEmpty: {
                            message: 'Please enter a first name.'
                        }
                    }
                },
4

1 回答 1

0

一种解决方案是使用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);

于 2017-12-06T15:28:55.930 回答