似乎动态添加customValidity打破了模式验证。有没有办法使用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>
答案 0 :(得分:3)
使用setCustomValidity
会将customError
property设置为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);
}