jQuery Validate单表单多区块表单:点击Next时逐区块校验实现方案
分步表单区块局部校验实现方案
核心逻辑
借助jQuery Validate插件自带的valid()手动校验方法,在点击Next按钮时仅校验当前显示区块的所有字段,校验通过才执行跳转,无需拆分原有单表单结构。
调整步骤
- 修正原有校验初始化的语法错误
- 在Next按钮点击事件的最开头增加当前区块的校验判断逻辑
- 原有跳转逻辑完全保留,仅增加拦截判断
代码修改示例
1. 修正后的表单校验初始化
// 关闭debug模式(调试用途,开启会阻止表单正常提交) jQuery.validator.setDefaults({ success: "valid" }); $("#myform").validate({ rules: { firstName: { required: true, normalizer: function(value) { return $.trim(value); } }, lastName: { required: true, normalizer: function(value) { return $.trim(value); } }, email: { required: true, email: true }, mobileNumber: { required: true, minlength: 10 } } });
2. 调整后的按钮点击事件
$(".button-next-pre").click(function() { var btnId = $(this).attr("id"); // 仅Next按钮触发跳转前执行局部校验 if (btnId === "next") { // 获取当前正在显示的区块(对应原有步骤索引child变量) var currentSection = $("section:nth-of-type(" + child + ")"); // 匹配当前区块内所有需要校验的表单字段 var fieldsToValidate = currentSection.find("input, select, textarea"); // 手动触发局部校验,校验失败直接终止后续跳转逻辑 var isValid = fieldsToValidate.valid(); if (!isValid) { return false; } } // 以下完全保留原有跳转逻辑 $("#svg_form_time rect").css("fill", active_color); $("#svg_form_time circle").css("fill", active_color); if (btnId == "next") { $("#prev").removeClass("disabled"); if (child >= length) { $(this).addClass("disabled"); $('#submit').removeClass("disabled"); } if (child <= length) { child++; } } else if (btnId == "prev") { $("#next").removeClass("disabled"); $('#submit').addClass("disabled"); if (child <= 2) { $(this).addClass("disabled"); } if (child > 1) { child--; } } var circle_child = child + 1; $("#svg_form_time rect:nth-of-type(n + " + child + ")").css("fill", base_color); $("#svg_form_time circle:nth-of-type(n + " + circle_child + ")").css("fill", base_color); var currentSection = $("section:nth-of-type(" + child + ")"); currentSection.fadeIn(); currentSection.css('transform', 'translateX(0)'); currentSection.prevAll('section').css('transform', 'translateX(-100px)'); currentSection.nextAll('section').css('transform', 'translateX(100px)'); $('section').not(currentSection).hide(); });
注意事项
- 错误提示会自动匹配原有样式,显示在对应字段后方,和全量提交校验的提示效果一致
- 后续新增表单区块时,只需在
validate的rules配置中补充对应字段的校验规则,无需修改跳转逻辑 - 最后点击提交按钮时仍会自动执行全表单的整体校验,符合原有预期
内容的提问来源于stack exchange,提问作者sandeep。
相关产品推荐
相关产品推荐

