jQuery 验证插件 - 在范围方法验证和错误消息中使用变量

jQuery Validate plugin - Using a variable in range method validation and error messaging

我正在使用 jQuery validate plugin 并使用 range 方法在我的第一个输入中要求 0100 之间的数字。在我的第二个输入中,我想要一个介于第一个输入的数字和 100 之间的数字。例如,如果您在第一个输入中输入 10,则第二个输入中的范围应介于 10100 之间。如果您要在第二个输入中输入 5,应该会出现 Please enter a value between 10 and 100 错误。这可能吗?

var rangeVal = null;

$('form').submit(function(e){
  return false;
});

$('#range').keyup(function() {
  rangeVal = $(this).val();
  console.log(rangeVal);
});

$('form').validate({
    rules: {
        range: {
            range: [0, 100]
        },
        range2: {
          range: [rangeVal, 100]
        }
    },
    messages: {
        range: {
          range: "Please enter a value between 0 and 100"
        },
        range2: {
          range: "Please enter a value between " + rangeVal + " and 100"
        }
    }
});
label {
  display:block;
  margin-top:10px;
}
input {
  display:block;
}
input[type="submit"] {
  margin-top:30px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.1/dist/jquery.validate.min.js"></script>
<form>
  <label>Range1 (0 - 100)
    <input id="range" name="range" type="number" />
  </label>
  <label>Range2 (Range1 - 100)
    <input id="range2" name="range2" type="number" />
  </label>
  <input type="submit" />
</form>

我能够通过将规则更改为函数并在消息中使用模板参数来解决此问题:

var rangeVal = null;

$('form').submit(function(e){
  e.preventDefault();
});

$('#range').keyup(function() {
  rangeVal = $(this).val();
});

$('form').validate({
    rules: {
        range: {
            range: [0, 100]
        },
        range2: {
            range: function () {
                return [rangeVal, 100];
            }
        },
    },
    messages: {
        range: {
          range: "Please enter a value between 0 and 100"
        },
        range2: {
          range: "Please enter a value between {0} and 100"
        }
    }
});
label {
  display:block;
  margin-top:10px;
}
input {
  display:block;
}
input[type="submit"] {
  margin-top:30px;
}
.error {
  color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.1/dist/jquery.validate.min.js"></script>
<form>
  <label>Range1 (0 - 100)
    <input id="range" name="range" type="number" />
  </label>
  <label>Range2 (Range1 - 100)
    <input id="range2" name="range2" type="number" />
  </label>
  <input type="submit" />
</form>