gpt4 book ai didi

javascript - Javascript 更改值时不检查 HTML 输入有效性

转载 作者:行者123 更新时间:2023-11-30 08:21:13 25 4
gpt4 key购买 nike

我有一个定义了 minlength 的文本输入。当用户输入文本时,输入的 validity 状态会立即更新。如果我更改代码中的值,有效性状态将重置为有效——即使违反了约束,validity.valid 仍为真。

const input = document.getElementById("input");
const label = document.getElementById("label");
document.getElementById("rightButton").addEventListener("click", evt => {
input.value = "ABCDE";
});
document.getElementById("wrongButton").addEventListener("click", evt => {
input.value = "AB";
});

setInterval(() => label.innerHTML = input.validity.valid, 250);
<input type="text" id="input" minlength="4">
<span id="label"></span>
<hr/>
<button id="rightButton">Make It Right</button>
<button id="wrongButton">Make It Wrong</button>

当我分配给 input.value 时,为什么自动有效性检查没有运行?这在某处记录了吗?有没有我可以调用的方法来触发浏览器的内部验证过程,而不必自己进行检查并调用 setCustomValidity

最佳答案

使用 pattern 是解决我的问题的合理方法,所有功劳都归功于 Sujil 促使我弄清楚这里到底发生了什么。我只是想为以后遇到这个问题的读者澄清一下。

来自 the spec for minlength (强调我的):

If an element has a minimum allowed value length, its dirty value flag is true, its value was last changed by a user edit (as opposed to a change made by a script), its value is not the empty string, and the code-unit length of the element’s value is less than the element’s minimum allowed value length, then the element is suffering from being too short.

这种语言(“最后由用户编辑更改”)也在 maxlength 的规范中,但不用于任何其他约束。这就是为什么没有“强制验证”方法的原因,因为所有约束一直都在应用,除了这两个。我不确定为什么,但它非常明确并得到普遍实现。

关于javascript - Javascript 更改值时不检查 HTML 输入有效性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53226031/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com