如何在“setCustomValidity(“...");"之后清除、删除或重置 HTML5 表单验证状态? [英] How to clear, remove, or reset HTML5 form validation state after "setCustomValidity("...");"?

查看:28
本文介绍了如何在“setCustomValidity(“...");"之后清除、删除或重置 HTML5 表单验证状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在setCustomValidity("...");之后清除、删除或重置HTML5表单验证状态?

设置空字符串 setCustomValidity("");,在 Firefox 和 Chrome 中关闭表单验证错误消息.我不想关闭表单验证错误消息.我想重置验证状态,以便可以检查下一个答案并保留显示的验证错误消息.如果验证状态没有被重置,那么即使是下一个正确的答案也会错误地显示验证错误消息.

<小时>

不知何故,清晰"意味着关闭"?

<块引用>

如果参数为空字符串,则清除自定义错误.

http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#the-constraint-validation-api

<小时>

这是一个验证测试用例:

<html dir="ltr" lang="en"><头><meta charset="utf-8"/><title>验证测试用例</title><身体><form id="testForm"><input type="text" id="answer" pattern="[A-Za-z]+" 需要自动对焦/><input type="submit" value="OK"/></表单><脚本>/*jslint 浏览器:true,vars:true,white:true,maxerr:50,缩进:4 */(功能 (){严格使用";无功形式=空;无功答案=空;var isCorrectAnswer = 函数(值){返回(值 ===a");};var closeValidation = 函数(元素){//如果显示,则关闭表单验证错误消息.element.blur();element.focus();};var validateForm = 函数(事件){event.preventDefault();event.stopPropagation();var isValidForm = event.target.checkValidity();如果(isValidForm){如果(isCorrectAnswer(answer.value)){表单.重置();关闭验证(答案);console.log("正确答案.");alert("正确答案.");}别的{console.log("错误答案.");answer.setCustomValidity("答案不正确.");answer.checkValidity();//answer.setCustomValidity("");}}};window.addEventListener("DOMContentLoaded", function (){form = document.getElementById("testForm");answer = document.getElementById("answer");form.addEventListener("submit", validateForm, false);}, 错误的);}());

输入不正确的答案,除了a"之外的任何字母,然后按 Enter.输入正确答案a",然后按 Enter.

不更改测试用例,Opera、Firefox 和 Chrome 中的行为是相同的(Chrome 错误除外).无论答案正确或不正确,验证错误消息都会持续存在.

现在,在 answer.setCustomValidity(""); 取消注释后,Opera 会清除自定义验证错误,但不会关闭验证错误消息,这正是我所期望的.另一方面,Firefox 和 Chrome 都清除了自定义验证错误并关闭了验证错误消息(bug?).

<小时>

BUG:Chrome 在第一次调用时不会checkValidity()".

在 Chrome 中,answer.checkValidity(); 在第一次提交后不显示验证消息.后续提交显示验证错误消息.

http://code.google.com/p/chromium/问题/详细信息?id=95970

BUG:在 Chrome 中,当输入更改时,验证错误消息为空白但未关闭.

http://code.google.com/p/chromium/问题/详细信息?id=95973

<小时>

Opera 11.51 内部版本 1087

火狐 6.0.2

谷歌浏览器 13.0.782.220 米

解决方案

如果在 'submit' 事件处理程序中调用 setCustomValidity(),则不会显示自定义验证消息.

@tkent:

<块引用>

我确认 Opera 11.50 符合您的预期,但 Firefox 6 和Chrome 14 没有.

但是,根据标准,Chrome 的行为是正确的.

http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#form-submission-algorithm

<块引用>

  1. 如果从 submit() 方法提交的标志没有设置,并且submitter 元素的 no-validate 状态为 false,然后交互验证表单的约束并检查结果:如果结果是否定的(约束验证的结论是无效的字段,可能会通知用户这一点)然后中止这些步骤.
  2. 如果从 submit() 方法提交的标志未设置,则触发一个可取消的简单事件,名为 submit,在表单中.如果阻止事件的默认操作(即,如果事件被取消)然后中止这些步骤.否则,继续(实际上是默认的action 是执行提交).

浏览器必须在提交"事件之前调用交互式验证被解雇.您需要在提交"事件之前调用 setCustomValidity()如果您希望浏览器显示验证消息.歌剧好像以错误的顺序处理这些步骤.注意 checkValidity() 在无论如何,您的代码没有任何效果.checkValidity() 从不显示验证消息.

http://code.google.com/p/chromium/问题/详细信息?id=95970

<小时>

[Bug 11287] 新功能:元素中的setCustomValidity"调用应使用oninput"事件...

@尼克:

<块引用>

元素中的setCustomValidity"调用应使用oninput"事件...

http://lists.w3.org/Archives/public/public-html/2010Nov/0186.html

<小时>

回复:[whatwg] 表单元素无效消息

@Mounir 拉穆里:

<块引用>

因此,您要做的是使元素在无效事件中有效太晚了.在无效事件之后,Firefox 尝试显示 UI使用返回空字符串的validationMessage形式有效.如果你想没有 UI,你应该取消事件但仍然取消提交.你应该使用onchange/oninput(强调)如果你想让表单改变有效性状态提交.

http://www.mail-archive.com/whatwg@lists.whatwg.org/msg23762.html

<小时>

解决方法是使用input"事件处理程序而不是submit"事件处理程序验证输入.

<html dir="ltr" lang="en"><头><meta charset="utf-8"/><title>验证测试用例</title><身体><form id="testForm"><input type="text" id="answer" pattern="[A-Za-z]+" 需要自动对焦/><input type="submit" value="OK"/></表单><脚本>/*jslint 浏览器:true,vars:true,white:true,maxerr:50,缩进:4 */(功能(控制台){严格使用";无功形式=空;无功答案=空;var isCorrectAnswer = 函数(值){返回(值 ===a");};var closeValidation = 函数(元素){//如果显示,则关闭表单验证错误消息.element.blur();element.focus();};var validateForm = 函数(事件){event.preventDefault();event.stopPropagation();var isValidForm = event.target.checkValidity();如果(isValidForm){console.log("正确答案.");关闭验证(答案);表单.重置();}别的{console.log("错误答案.");}};window.addEventListener("DOMContentLoaded", function (){form = document.getElementById("testForm");answer = document.getElementById("answer");form.addEventListener("submit", validateForm, false);answer.addEventListener("输入", function (){//如果值与模式匹配,则仅显示自定义表单验证错误消息.if (answer.value.match(new RegExp(answer.getAttribute("pattern")))){answer.setCustomValidity(isCorrectAnswer(answer.value) ? "" : "错误答案.");}}, 错误的);}, 错误的);}(window.console));

How to clear, remove, or reset HTML5 form validation state after setCustomValidity("...");?

Setting an empty string, setCustomValidity("");, in Firefox and Chrome closes the form validation error message. I do not want to close the form validation error message. I want to reset the validation state so that the next answer can be checked and also to keep the displayed validation error message. If the validation state is not reset, then even the next, correct answer will incorrectly show a validation error message.


So somehow, "clear" means "close"?

If the argument is the empty string, clears the custom error.

http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#the-constraint-validation-api


Here is a validation test case:

<!DOCTYPE html>
<html dir="ltr" lang="en">
    <head>
        <meta charset="utf-8"/>
        <title>Validation test case</title>
    </head>
    <body>
        <form id="testForm">
            <input type="text" id="answer" pattern="[A-Za-z]+" autofocus required/>
            <input type="submit" value="OK"/>
        </form>

        <script>
            /*jslint browser: true, vars: true, white: true, maxerr: 50, indent: 4 */
            (function ()
            {
                "use strict";

                var form = null;
                var answer = null;

                var isCorrectAnswer = function (value)
                {
                    return (value === "a");
                };

                var closeValidation = function (element)
                {
                    // Close the form validation error message if displayed.
                    element.blur();
                    element.focus();
                };

                var validateForm = function (event)
                {
                    event.preventDefault();
                    event.stopPropagation();

                    var isValidForm = event.target.checkValidity();
                    if (isValidForm)
                    {
                        if (isCorrectAnswer(answer.value))
                        {
                            form.reset();
                            closeValidation(answer);

                            console.log("Correct answer.");
                            alert("Correct answer.");
                        }
                        else
                        {
                            console.log("Incorrect answer.");
                            answer.setCustomValidity("Incorrect answer.");
                            answer.checkValidity();
                            //answer.setCustomValidity("");
                        }
                    }
                };

                window.addEventListener("DOMContentLoaded", function ()
                {
                    form = document.getElementById("testForm");
                    answer = document.getElementById("answer");

                    form.addEventListener("submit", validateForm, false);
                }, false);
            }());
        </script>
    </body>
</html>

Type an incorrect answer, any letters(s) but "a", and press Enter. Type the correct answer "a", and press Enter.

Without changes to the test case, the behavior is the same in Opera, Firefox, and Chrome (except the Chrome bugs). The validation error message persists regardless if the answer is correct or incorrect.

Now, after answer.setCustomValidity(""); is uncommented, Opera clears the custom validation error but does not close the validation error message, which is what I expect. On the other hand, Firefox and Chrome both clear the custom validation error and close the validation error message (bug?).


BUG: Chrome doesn't "checkValidity()" when first invoked.

In Chrome, answer.checkValidity(); doesn't show the validation message after the first submit. Subsequent submits show the validation error message.

http://code.google.com/p/chromium/issues/detail?id=95970

BUG: In Chrome, the validation error message is blanked but not closed when the input is changed.

http://code.google.com/p/chromium/issues/detail?id=95973


Opera 11.51 Build 1087

Firefox 6.0.2

Google Chrome 13.0.782.220 m

解决方案

A custom validation message is not shown if setCustomValidity() is called in 'submit' event handler.

@tkent:

I confirmed Opera 11.50 worked as your expectation, but Firefox 6 and Chrome 14 didn't.

However, Chrome's behavior is correct according to the standard.

http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#form-submission-algorithm

  1. If the submitted from submit() method flag is not set, and the submitter element's no-validate state is false, then interactively validate the constraints of form and examine the result: if the result is negative (the constraint validation concluded that there were invalid fields and probably informed the user of this) then abort these steps.
  2. If the submitted from submit() method flag is not set, then fire a simple event that is cancelable named submit, at form. If the event's default action is prevented (i.e. if the event is canceled) then abort these steps. Otherwise, continue (effectively the default action is to perform the submission).

Browsers must invoke the interactive validation BEFORE 'submit' event is fired. You need to call setCustomValidity() before 'submit' event if you want a browser to show a validation message. Opera seems to handle these steps in incorrect order. Note that checkValidity() in your code has no effect anyway. checkValidity() never shows a validation message.

http://code.google.com/p/chromium/issues/detail?id=95970


[Bug 11287] New: 'setCustomValidity' call in element should use 'oninput' event...

@Nick:

'setCustomValidity' call in element should use 'oninput' event...

http://lists.w3.org/Archives/Public/public-html/2010Nov/0186.html


Re: [whatwg] Form element invalid message

@Mounir Lamouri:

So, what you do is making the element valid in the invalid event which is too late. After the invalid event, Firefox tries to show the UI using the validationMessage which return the empty string when the form is valid. You should cancel the event if you want to have no UI at all but still cancel the submission. You should use onchange/oninput (emphasis added) to change the validity state if you want the form to be submitted.

http://www.mail-archive.com/whatwg@lists.whatwg.org/msg23762.html


The fix is to validate the input with the "input" event handler instead of the "submit" event handler.

<!DOCTYPE html>
<html dir="ltr" lang="en">
    <head>
        <meta charset="utf-8"/>
        <title>Validation test case</title>
    </head>
    <body>
        <form id="testForm">
            <input type="text" id="answer" pattern="[A-Za-z]+" autofocus required/>
            <input type="submit" value="OK"/>
        </form>

        <script>
            /*jslint browser: true, vars: true, white: true, maxerr: 50, indent: 4 */
            (function (console)
            {
                "use strict";

                var form = null;
                var answer = null;

                var isCorrectAnswer = function (value)
                {
                    return (value === "a");
                };

                var closeValidation = function (element)
                {
                    // Close the form validation error message if displayed.
                    element.blur();
                    element.focus();
                };

                var validateForm = function (event)
                {
                    event.preventDefault();
                    event.stopPropagation();

                    var isValidForm = event.target.checkValidity();
                    if (isValidForm)
                    {
                        console.log("Correct answer.");
                        closeValidation(answer);
                        form.reset();
                    }
                    else
                    {
                        console.log("Incorrect answer.");
                    }
                };

                window.addEventListener("DOMContentLoaded", function ()
                {
                    form = document.getElementById("testForm");
                    answer = document.getElementById("answer");

                    form.addEventListener("submit", validateForm, false);
                    answer.addEventListener("input", function ()
                    {
                        // Only show custom form validation error message if the value matches the pattern.
                        if (answer.value.match(new RegExp(answer.getAttribute("pattern"))))
                        {
                            answer.setCustomValidity(isCorrectAnswer(answer.value) ? "" : "Incorrect answer.");
                        }
                    }, false);
                }, false);
            }(window.console));
        </script>
    </body>
</html>

这篇关于如何在“setCustomValidity(“...");"之后清除、删除或重置 HTML5 表单验证状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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