【问题标题】:Validate a form dynamically inserted to the DOM验证动态插入到 DOM 的表单
【发布时间】:2018-05-20 12:18:55
【问题描述】:

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

我尝试了以下失败:

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

当前验证格式:

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

【问题讨论】:

  • 表单是通过什么方式动态插入的?
  • 我基本上只需要.on相当于formValidation。
  • 它使用 vue 插入

标签: javascript jquery formvalidation-plugin jquery-form-validator


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-28
    • 1970-01-01
    • 1970-01-01
    • 2013-12-31
    • 1970-01-01
    • 2013-02-17
    • 2013-05-13
    相关资源
    最近更新 更多