简体   繁体   English

自定义 HTML5 表单验证最初未显示自定义错误

[英]Custom HTML5 form validation not showing custom error initially

Basic HTML5 form with custom validation.带有自定义验证的基本 HTML5 表单。 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.如果您输入“abc”并按提交(或按回车键),该字段将被标记为无效,但不会出现错误消息。 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.这种双重提交行为出现在 Windows 和 OS X 上最新版本的 Firefox、Chrome、Safari 和 IE 上。您会注意到第一次提交时会出现默认的“此字段是必需的...”消息,并且没有显示奇怪的行为。

http://jsfiddle.net/6gsr3r4b/ http://jsfiddle.net/6gsr3r4b/

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;顺便说一句,我很清楚这个验证在旧版本的 IE 中不起作用,并且输入字段可能有一个number类型,可以自动完成这个验证; this is simplified example of my problem for demonstration purposes only.这是我的问题的简化示例,仅用于演示目的。

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>

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.如果值无效,它会在元素上触发无效事件,返回 false,然后以用户代理可用的任何方式向用户报告有效性状态。 Otherwise, it returns true.否则,它返回真。

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 attribute to 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.使用 title 属性来描述模式以帮助用户。 This attribute applies when the value of the type attribute is text, search, tel, url or email;当 type 属性的值为 text、search、tel、url 或 email 时,该属性适用; otherwise it is ignored.否则将被忽略。 The regular expression language is the same as JavaScript's.正则表达式语言与 JavaScript 相同。 The pattern is not surrounded by forward slashes.该模式没有被正斜杠包围。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM