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

问题描述 投票:0回答:1

我正在使用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/[email protected]/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>
jquery jquery-validate
1个回答
0
投票

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

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/[email protected]/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>
© www.soinside.com 2019 - 2024. All rights reserved.