如何从JavaScript函数手动显示HTML5验证消息? [英] How to manually show a HTML5 validation message from a JavaScript function?

查看:77
本文介绍了如何从JavaScript函数手动显示HTML5验证消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有任何方法可以使用JavaScript函数以编程方式显示HTML5验证错误。

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>
    <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.

推荐答案

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

You can now use the HTMLFormElement.reportValidity() method, at the moment it's implemented in most browsers except Internet Explorer (see Browser compatibility at MDN). It reports validity errors without triggering the submit event and they are shown in the same way.

这篇关于如何从JavaScript函数手动显示HTML5验证消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆