约束验证 DOM 方法
checkValidity() 方法
如果输入字段包含无效的数据,显示一条消息:
<input id="id1" type="number" min="100" max="300" required>
<button onclick="myFunction()">OK</button>
<p id="demo"></p>
<script>
function myFunction() {
var inpObj = document.getElementById("id1");
if (inpObj.checkValidity() == false) {
document.getElementById("demo").innerHTML = inpObj.validationMessage;
}
}
</script>
约束验证 DOM 属性
合法性属性
input 元素的 validity 属性包含了与数据合法性相关的一系列属性:
实例
如果输入字段中的数字大于 100(input 元素的 max 属性),则显示一条消息:
rangeOverflow 属性
<input id="id1" type="number" max="100">
<button onclick="myFunction()">OK</button>
<p id="demo"></p>
<script>
function myFunction() {
var txt = "";
if (
document.getElementById("id1").validity.rangeOverflow) {
txt = "值太大";
}
document.getElementById("demo").innerHTML = txt;
}
</script>
如果输入字段中的数字小于 100(input 元素的 min 属性),则显示一条消息:
rangeUnderflow 属性
<input id="id1" type="number" min="100">
<button onclick="myFunction()">OK</button>
<p id="demo"></p>
<script>
function myFunction() {
var txt = "";
if (document.getElementById("id1").validity.rangeUnderflow) {
txt = "值太小";
}
document.getElementById("demo").innerHTML = txt;
}
</script>