You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用jQuery Validation插件验证数组型数组输入框?

使用jQuery Validation插件验证数组型数组输入框

需求说明

每个child[*]输入框指定对应房间的孩子数量,同房间下的age[*][]输入框需要满足:

  • 当孩子数量为N时,前N个年龄输入框必须必填
  • 填写的年龄必须在1到12之间

第一步:修正HTML语法错误

原HTML存在引号未闭合的问题,会导致插件无法正常识别表单元素,修正后的代码如下:

<form id="transport-form">
  <div class="form-group">
    <label> Room1</label>
    <input type="text" name="child[0]" value="2">
    <input type="text" name="age[0][]">
    <input type="text" name="age[0][]">
  </div>
  <div class="form-group">
    <label> Room2</label>
    <input type="text" name="child[1]" value="2">
    <input type="text" name="age[1][]">
    <input type="text" name="age[1][]">
  </div>
  <input type="submit" value="submit">
</form>

第二步:配置jQuery Validation验证规则

由于jQuery Validation默认不支持age[*][]这种动态数组命名的直接规则绑定,需要通过动态遍历表单元素来添加验证规则,同时关联同房间的child[*]输入框值来判断必填条件:

// 初始化表单验证
$("#transport-form").validate({
  errorElement: "span",
  errorClass: "invalid-feedback"
});

// 遍历所有年龄输入框,绑定验证规则
$("input[name^='age[']").each(function() {
  const $ageInput = $(this);
  // 提取房间索引,比如从age[0][]里拿到0
  const roomIndex = $ageInput.attr("name").match(/\[(\d+)\]/)[1];
  // 找到同房间的child输入框
  const $childInput = $(`input[name='child[${roomIndex}]']`);
  // 获取当前年龄输入框在同房间里的索引
  const ageInputIndex = $(`input[name='age[${roomIndex}][]']`).index($ageInput);

  // 为当前年龄输入框添加验证规则
  $ageInput.rules("add", {
    required: function() {
      // 当child输入框的数值大于当前年龄框的索引时,必填
      const childCount = parseInt($childInput.val()) || 0;
      return ageInputIndex < childCount;
    },
    range: [1, 12],
    messages: {
      required: "该年龄为必填项",
      range: "年龄必须在1到12之间"
    }
  });
});

// 监听child输入框值变化,重新触发验证
$("input[name^='child[']").on("input change", function() {
  const roomIndex = $(this).attr("name").match(/\[(\d+)\]/)[1];
  $(`input[name='age[${roomIndex}][]']`).valid();
});

代码说明

  1. 初始化验证:先调用validate()初始化表单验证,配置错误提示的元素和样式。
  2. 动态绑定规则:通过each()遍历所有年龄输入框,提取房间索引和当前输入框的位置,关联同房间的孩子数量输入框,判断是否需要必填。
  3. 范围验证:使用range规则限制年龄在1-12之间。
  4. 动态触发验证:当孩子数量输入框的值变化时,重新触发对应房间年龄输入框的验证,确保规则实时生效。

内容的提问来源于stack exchange,提问作者B L Praveen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 08:34:51