27

I want to know if there is any way to programatically show a HTML5 validation error, using a JavaScript function.

This is useful for scenarios where email duplication has to be checked. For example, a person enters an email, presses the Submit button, and then has to be notified that this email is already registered or something.

I know there are other ways of showing such an error, but I wanted to display it in the same way as how the validation error messages are shown (e.g. invalid email, empty field, etc.).

JSFiddle: http://jsfiddle.net/ahmadka/tjXG3/

HTML Form:

<form>
    <input type="email" id="email" placeholder="Enter your email here..." required>
    <button type="submit">Submit</button>
</form>

<button id="triggerMsg" onclick="triggerCustomMsg()">Trigger Custom Message</button>

JavaScript:

function triggerCustomMsg()
{
    document.getElementById("email").setCustomValidity("This email is already used");

}

The above code sets the custom message, but its not automatically shown. It's only shown when the person presses the submit button or something.

4

4 回答 4

35

您现在可以使用 HTMLFormElement.reportValidity() 方法,目前它已在除 Internet Explorer 之外的大多数浏览器中实现(请参阅MDN 上的浏览​​器兼容性)。它在不触发提交事件的情况下报告有效性错误,并且它们以相同的方式显示。

于 2016-08-28T18:39:05.817 回答
22
var applicationForm = document.getElementById("applicationForm");    
if (applicationForm.checkValidity()) {
  applicationForm.submit();
} else {
  applicationForm.reportValidity();
}

reportValidity() 方法将触发 HTML5 验证消息。

于 2020-04-28T09:37:22.943 回答
5

这个问题是一年多前提出的,但这是我最近遇到的一个很好的问题......

我的解决方案是使用 JavaScript 在<label>each上创建一个属性(我使用“data-invalid”) <input><select><textarea>包含validationMessage

然后是一些 CSS...

label:after {
    content: attr(data-invalid);
   ...
}

... 显示错误消息。

限制

这仅在每个元素都有标签的情况下才有效。如果将属性放在元素本身上,它将不起作用,因为<input>元素不能有:after伪元素。

演示

http://jsfiddle.net/u4ca6kvm/2/

于 2014-11-20T04:21:32.020 回答
3

正如@Diego 所说,您可以使用 form.reportValidity();
为了支持 IE 和 Safari,请包含这个 polyfill,它可以正常工作:

if (!HTMLFormElement.prototype.reportValidity) {
    HTMLFormElement.prototype.reportValidity = function() {
      if (this.checkValidity()) return true;
      var btn = document.createElement('button');
      this.appendChild(btn);
      btn.click();
      this.removeChild(btn);
      return false;
    }
}
于 2017-04-08T20:15:13.540 回答