2010-04-14 86 views
11

我的HTML表單有一些div,這些是div嚮導的步驟。點擊「下一步」按鈕後,我只想驗證活動div。我正在使用jQuery.Validate.js插件。使用jQuery驗證插件驗證表單子集

每個div有一個ID,所以我想辦法這樣說:

wizardForm.validate().element('#first-step :input') 

但這只是驗證第一輸入,不是所有的人。 如何驗證div內的所有輸入?

+0

有在jqueryvalidation.org/files/demo/multipart一個例子(目前由於破混合內容)。它是特定於必填字段。 – TrueWill 2016-05-25 19:47:42

回答

24

以什麼jAndy的建議,我創造了這個輔助函數:

jQuery.validator.prototype.subset = function(container) { 
    var ok = true; 
    var self = this; 
    $(container).find(':input').each(function() { 
     if (!self.element($(this))) ok = false; 
    }); 
    return ok; 
} 

用法:

if (wizardForm.validate().subset('#first-step')) { 
    // go to next step 
} 
+0

很好的答案。我認爲這個功能應該是原生的插件。 [This](http://stackoverflow.com/questions/4625078/validate-different-fields-on-click-of-different-buttons-in-the-same-html-form-thr/5794770#5794770)是一個解決方案我用我的項目(看到這個之前)使用忽略選項和jQuery的:不是選擇器 – 2011-04-26 18:39:00

+0

這很好,但如果我不想使用它,那麼它不'驗證。 我的意思是 - 如果我使用包裝在IF中的form.validate()。subset('。container')方法,它就可以工作。 如果我只是試圖驗證窗體form.validate(); - 包裝在相同的IF,它不再工作。 任何想法爲什麼? 謝謝! – lehel 2017-11-08 10:44:17

1

我嘗試這種解決方案並沒有爲我工作。所以這裏是我如何實現相同的行爲,使用jquery.validation插件。

的驗證:

var form = $('#form'); 

    // init validator obj and set the rules 
    form.validate({ 
     errorElement: 'span', //default input error message container 
     errorClass: 'help-inline', // default input error message class 
     focusInvalid: false, // do not focus the last invalid input 
     ignore: "", 
     rules: { 
      // the rules, as usual 
     }, 

     highlight: function (element) { // hightlight error inputs 
      $(element).closest('.control-group').addClass('error'); // set error class to the control group 
     }, 

     unhighlight: function (element) { // revert the change dony by hightlight 
      $(element) 
       .closest('.control-group').removeClass('error'); // set error class to the control group 
     } 
    }); 

使用bootstrap form wizard

這是我如何驗證每個步驟:

$('#step :input').valid() 

就像一個魅力。

+0

這是如何驗證表單的一部分? – Dementic 2016-02-11 13:59:29

0

如果你看的選項options for the validate() function一個是ignore,默認情況下將阻止驗證從試圖驗證匹配CSS僞類:hidden任何領域。餘與FuelUX Wizard使用該組合,並能夠防止從嚮導進展到用下面的下一個步驟:

$('#wizard').wizard().on('change', function(event, info) { 
    if (! $('#wizard_form').valid()) event.preventDefault(); 
});