Javascript 如何在没有提交事件的情况下显示 setCustomValidity 消息/工具提示
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12785347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to show setCustomValidity message/tooltip without submit event
提问by Alexxandar
I'm using forms basic validation to check if email is correct format, then the data is sent by Ajax where it checks if email address is already in use and did the user select country/state or left default values in select boxes.
我正在使用表单基本验证来检查电子邮件的格式是否正确,然后数据由 Ajax 发送,它检查电子邮件地址是否已被使用以及用户是否选择了国家/州或在选择框中保留默认值。
But for HTML5 form validation to be done submit event is needed, upon clicking submit if it passes that basic form validation Ajax operation is performed, but then when results come in I would like to use the same browser tooltips for interface consistency (and well I like how they look).
但是要完成 HTML5 表单验证,需要提交事件,如果它通过了基本的表单验证 Ajax 操作,则在单击提交时执行,但是当结果出现时,我想使用相同的浏览器工具提示来保持界面一致性(而且我就像他们的样子)。
So is there a way to make them show up, I was unable to find if there is some special event for them or something like firing submit event but stopping it right away. Right now the field only gets a red edge and error message appears on hovering mouse over it, while the tooltip shows on again clicking submit button.
那么有没有办法让他们出现,我无法找到他们是否有一些特殊事件或诸如触发提交事件但立即停止之类的事情。现在该字段只有一个红色边缘,鼠标悬停在它上面时会出现错误消息,而再次单击提交按钮时会显示工具提示。
Also for browsers that don't have native tooltips(in my case Safari) I'm using Webshims Lib and it acts exactly the same as in Chrome and Firefox.
同样对于没有本机工具提示的浏览器(在我的情况下是 Safari),我使用的是 Webshims Lib,它的作用与 Chrome 和 Firefox 中的完全相同。
回答by Ben Boyle
I thought .checkValidity()
would do the trick, but it doesn't trigger the UI.
我认为.checkValidity()
可以解决问题,但它不会触发 UI。
It sounds like .reportValidity()
is going to do what you want.
http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#dom-cva-reportvalidity
听起来像是.reportValidity()
要做你想做的事。
http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#dom-cva-reportvalidity
I don't know if any browsers implement it yet though :/
我不知道是否有任何浏览器实现了它:/
回答by oldbam
You can find an answer at this link: How to force a html5 form validation without submitting it via jQuery
您可以在此链接中找到答案:如何在不通过 jQuery 提交的情况下强制进行 html5 表单验证
Basically, you find a submit button and call click on it:
基本上,你找到一个提交按钮并点击它:
// force form validation
document.getElementById("submitbutton").click()
You can also change validation message after checking if email address is in use or not and then force form validation as above:
您还可以在检查电子邮件地址是否正在使用后更改验证消息,然后按上述方式强制表单验证:
document.getElementById("email").setCustomValidity("This email is already registered!");
document.getElementById("submitbutton").click()
回答by Neil
It's actually very simple - add a hidden input element to your form:
它实际上非常简单 - 在表单中添加一个隐藏的输入元素:
<input type="hidden" id="myFormCheck" required="true" value=""/>
Call myInputField.setCustomValidity(message)
on the input element you want to create a custom tooltip on then call your form.click();
调用myInputField.setCustomValidity(message)
要在其上创建自定义工具提示的输入元素,然后调用您的form.click();
The form validity process runs and displays the message popup over that element, but the form won't submit because of the hidden element, so you won't need to catch and cancel the submit event.
表单有效性过程运行并在该元素上显示消息弹出窗口,但由于隐藏元素,表单不会提交,因此您不需要捕获和取消提交事件。
When you're done and really ready to go, set a value on the hidden element and the form will submit normally.
当您完成并真正准备好时,在隐藏元素上设置一个值,表单将正常提交。
This way you can use the form tooltip for something like checking for usernames that are available, or matching any value over an HTTP Request etc.
通过这种方式,您可以使用表单工具提示来检查可用的用户名,或通过 HTTP 请求匹配任何值等。
回答by thomasbabuj
Checkout this link ( Provide custom validation messages using setCustomValidity in HTML 5 pages).
查看此链接(在 HTML 5 页面中使用 setCustomValidity 提供自定义验证消息)。
In the above link, he used "input" type is number and oninput he called the validation function. Let me know is this what you are looking for.
在上面的链接中,他使用“输入”类型是数字,并且在输入时调用了验证函数。让我知道这就是你要找的。
<input type="number" required="true" value="50" min="18" max="60" step="1" oninput="validate(this)">
回答by Christian d'Heureuse
A polyfill for HTMLFormElement.reportValidity()
.
Tested with IE11 and Edge. But when running in the StackOverflow sandbox below with IE11, the validation messages are not displayed.
一个 polyfill 用于HTMLFormElement.reportValidity()
.
用 IE11 和 Edge 测试。但是当使用 IE11 在下面的 StackOverflow 沙箱中运行时,不会显示验证消息。
function reportValidityPolyfill() {
const button = createInvisibleSubmitButton();
this.appendChild(button);
this.addEventListener("submit", submitEventHandler);
var isValid = false;
button.click();
this.removeEventListener("submit", submitEventHandler);
this.removeChild(button);
return isValid;
function createInvisibleSubmitButton() {
const button = document.createElement("button");
button.type = "submit";
button.style.display = "none";
return button;
}
function submitEventHandler(event) {
event.preventDefault();
isValid = true;
}
}
if (!HTMLFormElement.prototype.reportValidity) {
HTMLFormElement.prototype.reportValidity = reportValidityPolyfill;
console.log("ReportValidity polyfill installed.");
} else {
console.log("ReportValidity polyfill skipped.");
}
input {
outline: 1px solid #0f0;
}
input:invalid {
outline: 1px solid #f00;
}
<form id="form1">
Enter a number from 1 to 5: <input type="number" min="1" max="5" required>
</form>
<br>
<div onclick="console.log('Validity: ' + document.getElementById('form1').reportValidity())">
Click here to call reportValidity()
</div>
回答by Ma Jerez
As most people say you have to use input.setCustomValidity("message")
.
正如大多数人所说,您必须使用input.setCustomValidity("message")
.
The problem here is that you can't check that validation within the submit
event, since you need to do an ajax call and then set setCustomValidity
asynchronously.
这里的问题是您无法在submit
事件中检查该验证,因为您需要执行 ajax 调用然后setCustomValidity
异步设置。
So basically you have to use the change
event of the input field and make the ajax call on every change. Or remove the submit button and use the click
event of a normal button, check the unique email in the ajax call and then call submit through javascript.
所以基本上你必须使用change
输入字段的事件并在每次更改时进行 ajax 调用。或者去掉提交按钮,使用click
普通按钮的事件,在ajax调用中查看唯一的email,然后通过javascript调用submit。
See an example of the last option using jQuery:
查看使用 jQuery 的最后一个选项的示例:
<form action="/sign-in" id="form">
<input type="email" id="email" required/>
<button id="submit">Submit</button>
</form>
// we capture the click instead the submit
$("#submit").on("click",function(){
var $elem = $("#email");
var email = $elem.val();
//the ajax call returns true if the email exists
$.get( "ajax/checkUniqueEmail", function(data) {
if(data === "true"){
$elem.setCustomValidity("This email already exists.");
}else{
$elem.setCustomValidity("")
}
//then we submit the form
$("#form").submit();
});
});
回答by zelusp
Here's a nice live examplethat custom validates/gives feedback on a form input.
这是一个很好的现场示例,自定义验证/提供表单输入的反馈。
The basic javascript looks like:
基本的 javascript 看起来像:
function checkPasscode() {
var passcode_input = document.querySelector("#passcode");
if (passcode_input.value != "Ivy") {
passcode_input.setCustomValidity("Wrong. It's 'Ivy'.");
} else {
passcode_input.setCustomValidity(""); // be sure to leave this empty!
alert("Correct!");
}
}
HTML:
HTML:
<form>
<label for="passcode">Enter Passcode:</label>
<input id="passcode"
type="password"
placeholder="Your passcode"
oninput="checkPasscode();"
required/>
<button type="submit">Submit</button>
</form>
回答by Ivan Ivkovi?
You can use setCustomValidity with for the element if the condition is false ( you can do it inside any event handler such as keypress or click ). If the input is NOT valid, SUBMIT. This will trigger the browser's message tooltip.
如果条件为假,您可以对元素使用 setCustomValidity with (您可以在任何事件处理程序中执行此操作,例如 keypress 或 click )。如果输入无效,则提交。这将触发浏览器的消息工具提示。