1.checkValidity()方法 如果input 元素包含有效数据,返回true,反之
2.setCustomValidity()方法 设置input元素的validationMessage属性
eg:
<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");
//因为Input中有了min与max条件,满足条件inpObj.checkValidity()输出true,反之
if (inpObj.checkValidity() == false) {
document.getElementById("demo").innerHTML = inpObj.validationMessage;
}
}
</script>
2. 约束验证DOM属性:
validity属性: 包含与Input元素的合法性相关的布尔属性; https://www.w3school.com.cn/js/js_validation_api.asp
validationMessage 包含当validity为false的浏览器显示的消息;
<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>
posted on
浙公网安备 33010602011771号