简体   繁体   English

jQuery:提交前验证字段(多步骤表单)

[英]jQuery: Validating fields before submitting (multistep form)

I have a form which consists of 2 steps. 我有一个包含2个步骤的表格。 What I'd like to do is validate each step before continuing to the next; 我想做的是在继续下一步之前验证每个步骤。 the user should not be able to get to step 2 of step 1's fields are invalid. 用户应该无法进入步骤1的步骤2的字段无效。

js fiddle: http://jsfiddle.net/Egyhc/ js小提琴: http//jsfiddle.net/Egyhc/
Below you can find the simplified version of the form: 您可以在下面找到表格的简化版:

<form>
  <div id="step1" style="display: block;">
    <label for="first_name">First Name</label>
    <input type="text" value="" name="first_name" id="FirstName"/>

    <label for="last_name">Last Name</label>
    <input type="text" value="" name="last_name" id="LastName"/>
  </div>


  <div id="step2" style="display: none;">
    <label for="first_name">Address</label>
    <input type="text" value="" name="address" id="Address"/> 
  </div>

  <a href="#" id="step1_btn">Continue to step 2</a>
  <input type="submit" id="submit_btn" value="Verstuur" style="display: none;" />
</form>

$(function() {
  $('#step1_btn').click(function() {
    $('#step1').hide();
    $('#step2, #submit_btn').show();        
  });
});​

How do you guys suggest I achieve this? 你们如何建议我实现这一目标?

There's a very neat setting of jQuery validate that lets you ignore validation on hidden fields. jQuery validate有一个非常简洁的设置,可让您忽略对隐藏字段的验证。 So you can handle the show/hide logic of your steps and for validation you could just do this: 因此,您可以处理步骤的显示/隐藏逻辑,而对于验证,您可以执行以下操作:

As this suggests: ignore hidden 如此暗示: 忽略隐藏

$("form").validate({
   ignore: ":hidden"
});

If you need to check for validation on something besides the default form submit, you can use the valid method like this: $("form").valid() . 如果您需要检查默认表单提交之外的其他内容的验证,则可以使用如下valid方法: $("form").valid()

I noticed you don't have any validation classes on your form, so I'm assuming you're handling that somewhere else. 我注意到您的表单上没有任何验证类,因此我假设您正在其他地方进行处理。 Just in case you're not, you can tell jQuery validate your rules through css classes like this: <input type="text" class="required digits"/> 以防万一,您可以告诉jQuery通过CSS类验证您的规则,如下所示: <input type="text" class="required digits"/>

See more here: http://bassistance.de/2008/01/30/jquery-validation-plugin-overview/ 在此处查看更多信息: http : //bassistance.de/2008/01/30/jquery-validation-plugin-overview/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM