2015-07-20 55 views
0

我有一個表格,只有數字驗證的文本框。錯誤顯示在jQueryUI模式窗口中。但是,當在文本框中輸入非數字時,我最終會多次出現相同的錯誤消息。而我輸入的非數字值越多,我得到的重複數就越多。任何建議將不勝感激。驗證文本框中的數字與jQuery驗證

這裏是初始驗證

enter image description here

這裏是驗證部分固定

enter image description here

這裏是驗證消息時,我輸入一個非數字的值。注意多個Please enter only digits消息。

enter image description here

這裏是代碼。

var valForm = function(kit_id) { 
    var form = $("#frm_" + kit_id); 
    var strErrors = "<ul>"; 

     form.validate({ 
      errorClass: "error-class", 
      errorElement: "div", 
      errorPlacement: function(error, element) { 
       console.log(error); 
       strErrors += "<li>" + error[0].innerHTML + "</li>"; 
       $("#error_modal").html(""); 
       $("#error_modal").html(strErrors + "</ul>"); 
      } 
     }); 

     form.find('input[name^="kit_name_"]').each(function() { 
      $(this).rules("add", { 
       required: true, 
       messages: { 
        required: "Please enter a name." 
       } 
      }) 
     }); 

     form.find('input[name^="kit_desc_"]').each(function() { 
      $(this).rules("add", { 
       required: true, 
       messages: { 
        required: "Please enter a description." 
       } 
      }); 
     }); 

     form.find('input[name^="kit_qty_"]').each(function() { 
      $(this).rules("add", { 
       required: true, 
       digits: true, 
       messages: { 
        required: "Please enter a quantity." 
       } 
      }); 
     }); 

     if (! form.valid()) { 
      $("#error_modal").dialog().siblings(".ui-dialog-titlebar").remove(); 
      strErrors = ""; 
     } else { 
      form.submit(); 
     } 
    }; 
+0

每次調用'errorPlacement'函數時,都會將當前錯誤附加到'strErrors'。沒有任何東西能夠從中去除舊的錯誤,所以它只是增長和增長。 – Barmar

+0

在jqueryvalidation.org網站上查看此示例:http://jqueryvalidation.org/files/demo/errorcontainer-demo.html – Barmar

回答

1

你的問題是由執行errorPlacement引起...

errorPlacement: function(error, element) { 
    console.log(error); 
    strErrors += "<li>" + error[0].innerHTML + "</li>"; 
    $("#error_modal").html(""); 
    $("#error_modal").html(strErrors + "</ul>"); 
} 

默認情況下,該插件會在網頁錯誤消息元素,並把它按任何errorPlacement功能到位。然後,無論何時錯誤更改或清除,插件都會自動更新錯誤消息元素的內容並切換它。您的代碼不斷創建新消息,並且該插件找不到要更新或切換的錯誤消息元素。

換句話說,errorPlacement僅用於爲每個輸入元素一次放置一條錯誤消息。你試圖強制它完全變成別的東西。

你想在你的模態中的錯誤摘要?如果是這樣,那麼你需要參考文檔並使用the showErrors option,這是爲創建自定義錯誤摘要而設計的。