似乎动态添加customValid正在破坏模式验证。有没有办法使用Javascript解决这个问题?
<html>
<head>
<title>Append validation issue</title>
<script>
function dothis(){
var f = document.createElement("form");
var i = document.createElement("input");
i.type = "text";
i.pattern = "[A-Z]{3}";
i.setCustomValidity("watch me break");
var s = document.createElement("input")
s.type = "submit";
f.appendChild(i);
f.appendChild(s)
document.getElementById("core").appendChild(f);
}
</script>
</head>
<body>
<div onclick="dothis()">click</div>
<div id="core"></div>
</body>
</html>
使用 setCustomValidity
会将 customError
属性设置为 true,因此该元素将始终无效。
因此,我们应该在文本无效时使用setCustomValidity
,在有效时使用清晰。
function dothis(){
var f = document.createElement("form");
var i = document.createElement("input");
i.type = "text";
i.pattern = "[A-Z]{3}";
i.oninput = function() {
this.setCustomValidity('');
}
i.oninvalid = function() {
this.setCustomValidity("watch me break");
}
var s = document.createElement("input")
s.type = "submit";
f.appendChild(i);
f.appendChild(s)
document.getElementById("core").appendChild(f);
}
https://jsfiddle.net/oL07go4s/