2016-08-05 33 views
0

我有得到在彈出交替顯示兩種形式,一種爲編輯(這是由AJAX加載),一個創造。如何處理一個頁面上的兩個表單進行驗證?

我想使用jQuery驗證同時顯示在編輯和提交字段提示。

一些驗證涉及的時間跨度不得重複。

這適用於創作,但我創建用於編輯的新規則並沒有被觸發,因爲創建規則優先。

我加入類規則,因爲規則我創建通過名稱或ID不知何故沒有得到積極的所有,也許是因爲我感到困惑的JQuery驗證插件如何工作。這些規則在代碼片段中被註釋掉了。

var classRules = {}; 

classRules['thresholdStartTime'] = {}; 
classRules['thresholdStartTime'][globalThresholdCheckName] = $form 
classRules['thresholdEndTime'] = {}; 
classRules['thresholdEndTime'][globalThresholdCheckName] = $form 

/* 
* 
for(var q = 0; q<20; ++q) { 
    validationrules['thresholdStartTime' + q] = {}; 
    validationrules['thresholdStartTime' + q]['required'] = true; 
    validationrules['thresholdStartTime' + q][globalThresholdCheckName] = $form 

    validationrules['thresholdEndTime' + q] = {}; 
    validationrules['thresholdEndTime' + q]['required'] = true; 
    validationrules['thresholdEndTime' + q][globalThresholdCheckName] = $form 

} 
*/ 

for(var cls in classRules) { 
    var rule = classRules[cls]; 
    $.validator.addClassRules(cls, rule); 
} 

//return validationrules as rm.rules here 

//in the caller, get validationrules from result 
var editForm = $('#editForm') 
.validate(
     { 
      rules : rm.rules, 
      classRules: rm.classRules, 
      messages : rm.messages, 
      success : $.noop 
     }); 
+0

感謝大家幫助。看起來驗證首次配置時會首選,因此忽略同一表單的第二條驗證命令。 – Adder

回答

1

使該表單的默認操作是防止e.preventDefault(),然後提交使用jQuery.ajax(),選擇什麼data發送,然後綁定該ajax請求表單的submit按鈕。這樣做對每種形式:

jQuery('.bidvalue').click(function(e) { 
    e.preventDefault(); 
    jQuery.ajax({ 
     type: 'POST', 
     url: ajaxurl, 
     data: 'action=newbid&id='+e.target.name, 
     success: function(msg){ 
      jQuery('#vehicle-value-box'+e.target.name).html(msg+',00€'); 
     } 
}); 

編輯,因爲我完全錯過了實際問題...

爲每個表單,您可以指定驗證如下:

$('#myform1').validate({ 
    rules: { 
     myfield1: { 
      required: true, 
      minlength: 3 
     }, 
     myfield2: { 
      required: true, 
      email: true 
     } 
    } 
}); 

但您必須更具體,並顯示兩種形式的HTML,也許你想要什麼驗證規則,f或者我真的很有幫助地回答你的問題。

編輯#2:從評論中添加一些東西(榮譽給Vicente Olivert Riera輸入)。

如果你想切換何種形式在申請驗證,這樣做:

var activeForm; 

$("form").focus(e => { 
    e.validate({ 
     rules: { 
      myfield1: { 
       required: true, 
       minlength: 3 
      }, 
      myfield2: { 
       required: true, 
       email: true 
      } 
     } 
    }); 
}); 

如果你有很多形式,只是想只有符合特定條件的具體形式:

$("form").focus(e => { 
    // Some criteria to check against for the form. 
    // Obviously you could make a crafty selector and avoid `if (e.hasClass())`, 
    // but this is to demonstrate using if to test the form if you wanted to check the form element in any way before applying `.validate()`. 
    if (e.hasClass("someClass") { 
     e.validate(...); 
    } 
}); 
+0

這和我的問題有關嗎? – Adder

+0

...你想在同一頁面上提交多個表單嗎? –

+0

不,我想有同時啓動一個形式中,並且具有在表單字段驗證是棘手的部分。 – Adder

相關問題