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

时间:2019-06-01 12:42:48

标签: javascript html forms validation input

我有以下代码:

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>

在提交但未填写该字段的情况下将显示弹出窗口“请填写此字段”。如何触发该弹出窗口,但带有我的自定义验证消息?

2 个答案:

答案 0 :(得分:1)

您可以通过使用.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">

答案 1 :(得分:0)

您可以在下面的代码中自定义默认验证消息,但是我不愿意进行其他验证,如果您也想进行其他验证,请自定义更多

表格代码

<form action="" method="get">
    <input type="text" name="a" id="a">
    <input type="text" name="b" id="b" required>
    <button type="submit">Submit</button>
</form>

Js代码

document.addEventListener("DOMContentLoaded", function() {
    var elements = document.getElementsByTagName("input");
    for (var inp of elements) {
        inp.oninvalid = function(e) {
            e.target.setCustomValidity("");
            if (!e.target.validity.valid) {
                e.target.setCustomValidity("Change Validation Message");
            }
        };
        inp.oninput = function(e) {
            e.target.setCustomValidity("");
        };
    }
})