2015-06-21 78 views
1

我試圖設置使用Parsely.js驗證插件的多步驟表單驗證。Parsley.js - 所有形式的一個多步驟函數

我跟隨這裏的文檔:「http://parsleyjs.org/doc/examples/multisteps.html」 - 但唯一的問題是我會有幾個表單,將跨越整個網站多個​​步驟,並在一些頁面將有不止一個。

提供僅支持每次一個形式的片斷,我需要指定不同的形式的ID如下顯示:

<script type="text/javascript"> 
$(document).ready(function() { 
    $('.next').on('click', function() { 
    var current = $(this).data('currentBlock'), 
     next = $(this).data('nextBlock'); 

    // only validate going forward. If current group is invalid, do not go further 
    // .parsley().validate() returns validation result AND show errors 
    if (next > current) 
     if (false === $('#demo-form').parsley().validate('block' + current)) 
     return; 

    // validation was ok. We can go on next step. 
    $('.block' + current) 
     .removeClass('show') 
     .addClass('hidden'); 

    $('.block' + next) 
     .removeClass('hidden') 
     .addClass('show'); 

    }); 
}); 
</script> 

是否有辦法來調整段,這樣它會自動如果表單檢測有多個步驟並相應地應用適當的行爲/設置?而不是必須一遍又一遍地爲每個表單複製該片段。

下面是HTML會是什麼樣子:

<form id="demo-form" data-parsley-validate> 
    <div class="first block1 show"> 
    <label for="firstname">Firstname:</label> 
    <input type="text" name="firstname" data-parsley-group="block1" required/> 

    <label for="lastname">Lastname:</label> 
    <input type="text" name="lastname" data-parsley-group="block1" required /> 
    <span class="next btn btn-info pull-right" data-current-block="1" data-next-block="2">Next ></span> 
    </div> 

    <div class="second block2 hidden"> 
    <label for="fullname">Email:</label> 
    <input type="text" name="fullname" required data-parsley-type="email" data-parsley-group="block2" /> 
    <span class="next btn btn-info pull-left" data-current-block="2" data-next-block="1">< Previous</span> 
    <input type="submit" class="btn btn-default pull-right" /> 
    </div> 
</form> 

回答

2

您需要更改代碼來指定用戶當前使用的形式。我已經改變了你使用的代碼塊,包括評論:

$(document).ready(function() { 
    $('.next').on('click', function() { 
    // Find the form whose button was just clicked 
    var currentForm = $(this).parents('form').first(); 

    var current = $(this).data('currentBlock'), 
    next = $(this).data('nextBlock'); 

    // only validate going forward. If current group is invalid, do not go further 
    // .parsley().validate() returns validation result AND show errors 
    if (next > current) 
     // Use currentForm found above here, rather than hard coded form id 
     if (false === currentForm.parsley().validate('block' + current)) 
     return; 

    // validation was ok. We can go on next step. 
    // Hide current block on current form 
    currentForm.find('.block' + current) 
     .removeClass('show') 
     .addClass('hidden'); 

    // Show next block on current form 
    currentForm.find('.block' + next) 
     .removeClass('hidden') 
     .addClass('show'); 
    }); 
}); 
+0

非常感謝你! – Leo