我正在使用jQuery validate plugin,并且正在使用range
方法在我的第一个输入中要求0
和100
之间的数字。在第二个输入中,我想输入一个介于第一个输入和100
之间的数字。例如,如果在第一个输入中输入10
,则范围应在第二个输入中在10
和100
之间。如果要在第二个输入中输入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>
我能够通过将规则更改为函数并在消息中使用模板参数来解决此问题:
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>