Parsley.js - 所有表格的一个多步骤功能

Parsley.js - one multi steps function for all forms

我正在尝试使用 Parsely.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>

有没有办法调整代码片段,使其自动检测表单是否有多个步骤并相应地应用适当的 behavior/settings?而不是必须为每个表单一遍又一遍地复制该片段。

下面是 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>

您需要更改代码以指定用户当前使用的表单。我已经更改了您用于执行此操作的代码块,包括注释:

$(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');
  });
});