gpt4 book ai didi

javascript - 手动设置自定义验证消息时如何触发 HTML5 验证错误弹出窗口?

转载 作者:行者123 更新时间:2023-12-02 23:33:04 28 4
gpt4 key购买 nike

我有以下代码:

document.getElementById('testSubmit').addEventListener('click', (e) => {
e.preventDefault();
document.getElementById('test').setCustomValidity('THIS WILL ALWAYS BE AN ERROR, how do I display this message?');
console.log(document.getElementById('test').validationMessage);
});
<input id = "test" type = "email" required>
<input id = "testSubmit" type = "submit">

如您所见,我可以指出输入字段中发生了错误。但是,我想在我的 input.validationMessage 中显示该消息,该消息是由我的错误弹出窗口中的 setCustomValidity 方法设置的(不会出现)。如何让 UI 验证错误弹出窗口出现。作为引用,我所指的弹出窗口可以在以下代码中看到:

document.getElementById('btn-submit').addEventListener("click", function() {
if (!document.getElementById('form').checkValidity()) {
document.getElementById("submit-hidden").click();
}
});
<form id="form" action="">

<input type="text" required />
<input id="submit-hidden" type="submit" style="display: none" />

</form>

<button id="btn-submit">Submit</button>

当您提交但未填写该字段时,会显示弹出窗口“请填写此字段”。如何使用自定义验证消息触发该弹出窗口?

最佳答案

您可以使用 .reportValidity() 来做到这一点。这是一个例子:

document.getElementById('testSubmit').addEventListener('click', (e) => {
e.preventDefault();
document.getElementById('test').setCustomValidity('THIS WILL ALWAYS BE AN ERROR, how do I display this message?');
document.getElementById('test').reportValidity();
});
<input id = "test" type = "email" oninput="validateInput();" required>
<input id = "testSubmit" type = "submit">

关于javascript - 手动设置自定义验证消息时如何触发 HTML5 验证错误弹出窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56406865/

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