javascript 自定义 HTML5 表单验证最初未显示自定义错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26613589/
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
Custom HTML5 form validation not showing custom error initially
提问by Jason
Basic HTML5 form with custom validation. If the submitted value is not a number, the browser should display the error message "Field must be an number." If you enter "abc" and press submit (or hit enter) the field is marked as invalid, but the error message does not appear. Press submit again (or hit enter) and it will show the message. This double-submit behavior appears on latest versions of Firefox, Chrome, Safari, and IE on Windows and OS X. You will notice that the default "this field is required..." message appears upon the first submission and does not exhibit the odd behavior.
带有自定义验证的基本 HTML5 表单。如果提交的值不是数字,则浏览器应显示错误消息“字段必须是数字”。如果您输入“abc”并按提交(或按回车键),该字段将被标记为无效,但不会出现错误消息。再次按提交(或按回车键),它将显示消息。这种双重提交行为出现在 Windows 和 OS X 上最新版本的 Firefox、Chrome、Safari 和 IE 上。您会注意到第一次提交时会出现默认的“此字段是必需的...”消息,并且没有出现奇怪的行为。
As an aside, I am well aware that this validation will not work in older versions of IE and that the input field could have a type of number
that would automatically complete this validation; this is simplified example of my problem for demonstration purposes only.
顺便说一句,我很清楚此验证在旧版本的 IE 中不起作用,并且输入字段可能具有number
自动完成此验证的类型;这是我的问题的简化示例,仅用于演示目的。
Javscript
脚本
var form = document.getElementById("form");
var field = document.getElementById("field");
form.onsubmit = validateForm;
function validateForm() {
if(isNaN(field.value)) {
field.setCustomValidity("Field must be a number.");
} else {
return true;
}
return false;
}
HTML
HTML
<form id="form">
<label for="field">Favorite number</label>
<input type="text" id="field" required>
<input type="submit">
</form>
回答by Woodrow Barlow
After setting the validity message, you need to call element.reportValidity()
to make it show up.
设置有效性消息后,需要调用element.reportValidity()
才能显示。
setCustomValidity(message)
Sets a custom error message string to be shown to the user upon submitting the form, explaining why the value is not valid — when a message is set, the validity state is set to invalid. To clear this state, invoke the function with an empty string passed as its argument. In this case the custom error message is cleared, the element is considered valid, and no message is shown.
reportValidity()
Checks the element's value against its constraints and also reports the validity status; if the value is invalid, it fires an invalid event at the element, returns false, and then reports the validity status to the user in whatever way the user agent has available. Otherwise, it returns true.
setCustomValidity(message)
设置在提交表单时向用户显示的自定义错误消息字符串,解释该值无效的原因——当设置消息时,有效性状态设置为无效。要清除此状态,请使用作为参数传递的空字符串调用该函数。在这种情况下,自定义错误消息被清除,元素被认为是有效的,并且不显示任何消息。
reportValidity()
根据其约束检查元素的值并报告有效性状态;如果值无效,它会在元素上触发无效事件,返回 false,然后以用户代理可用的任何方式向用户报告有效性状态。否则,它返回真。
You also need to use event.preventDefault()
on the form submission event whenever the input is invalid, so that the form submission doesn't go through.
event.preventDefault()
每当输入无效时,您还需要在表单提交事件上使用,以便表单提交不会通过。
Here is an example:
下面是一个例子:
var form = document.getElementById('form');
var field = document.getElementById('field');
form.onsubmit = validateForm;
/* this is the function that actually marks the field as valid or invalid */
function validateForm(event) {
if (isNaN(field.value)) {
field.setCustomValidity('Field must be a number.');
field.reportValidity();
event.preventDefault();
}
field.setCustomValidity('');
}
<form id="form">
<label for="field">Favorite number</label>
<input type="text" id="field" required />
<input type="submit" />
</form>
You can also use the HTML5 pattern attributeto do most form validation without JavaScript, or augmented with JavaScript to set custom error messages.
您还可以使用 HTML5模式属性在不使用 JavaScript 的情况下执行大多数表单验证,或者使用 JavaScript 进行扩充以设置自定义错误消息。
Pattern: A regular expression that the control's value is checked against. The pattern must match the entire value, not just some subset. Use the title attribute to describe the pattern to help the user. This attribute applies when the value of the type attribute is text, search, tel, url or email; otherwise it is ignored. The regular expression language is the same as JavaScript's. The pattern is not surrounded by forward slashes.
模式:检查控件值的正则表达式。模式必须匹配整个值,而不仅仅是某个子集。使用标题属性来描述模式以帮助用户。当 type 属性的值为 text、search、tel、url 或 email 时,该属性适用;否则将被忽略。正则表达式语言与 JavaScript 相同。该模式没有被正斜杠包围。
<form id="form">
<label for="field">Favorite number</label>
<input type="text" id="field" pattern="\d*" title="Field must be a number." required />
<input type="submit" />
</form>