JavaScript表单验证:理解函数调用

JavaScript表单验证:理解函数调用,javascript,forms,function,validation,handler,Javascript,Forms,Function,Validation,Handler,我对JavaScript完全是个新手,试图在表单验证方面找到自己的方法。我一直在阅读书籍和在线教程,我在网上发现了以下代码,在我看来,这些代码非常优雅且易于维护。不幸的是,我的JavaScript技能还不足以理解所有内容。我在这里请求您帮助理解定义的不同功能 我还想在一个事件(onSubmit事件)上调用InstantValidation函数,在一个独立的.js文件(基于事件侦听器)中调用它,那么您是否可以帮助我适当地调用该函数 以下是代码: <html> <body>

我对JavaScript完全是个新手,试图在表单验证方面找到自己的方法。我一直在阅读书籍和在线教程,我在网上发现了以下代码,在我看来,这些代码非常优雅且易于维护。不幸的是,我的JavaScript技能还不足以理解所有内容。我在这里请求您帮助理解定义的不同功能

我还想在一个事件(onSubmit事件)上调用InstantValidation函数,在一个独立的.js文件(基于事件侦听器)中调用它,那么您是否可以帮助我适当地调用该函数

以下是代码

<html>

<body>

    <form id="myform" action="#" method="get">
        <fieldset>

            <legend><strong>Add your comment</strong></legend>

            <p>
                <label for="author">Name <abbr title="Required">*</abbr></label>
                <input name="author" id="author" value="" 
                    required="required" aria-required="true" 
                    pattern="^([- \w\d\u00c0-\u024f]+)$"
                    title="Your name (no special characters, diacritics are okay)"
                    type="text" spellcheck="false" size="20" />
            </p>

            <p>
                <label for="email">Email <abbr title="Required">*</abbr></label>
                <input name="email" id="email" value=""
                    required="required" aria-required="true" 
                    pattern="^(([-\w\d]+)(\.[-\w\d]+)*@([-\w\d]+)(\.[-\w\d]+)*(\.([a-zA-Z]{2,5}|[\d]{1,3})){1,2})$"
                    title="Your email address"
                    type="email" spellcheck="false" size="30" />
            </p>

            <p>
                <label for="website">Website</label>
                <input name="website" id="website" value=""
                    pattern="^(http[s]?:\/\/)?([-\w\d]+)(\.[-\w\d]+)*(\.([a-zA-Z]{2,5}|[\d]{1,3})){1,2}(\/([-~%\.\(\)\w\d]*\/*)*(#[-\w\d]+)?)?$"
                    title="Your website address"
                    type="url" spellcheck="false" size="30" />
            </p>

            <p>
                <label for="text">Comment <abbr title="Required">*</abbr></label>
                <textarea name="text" id="text" 
                    required="required" aria-required="true" 
                    title="Your comment" 
                    spellcheck="true" cols="40" rows="10"></textarea>

            </p>

        </fieldset>
        <fieldset>

            <button name="preview" type="submit">Preview</button>
            <button name="save" type="submit">Submit Comment</button>

        </fieldset>

    </form>



    <script type="text/javascript">
    (function()
    {

        //add event construct for modern browsers or IE
        //which fires the callback with a pre-converted target reference
        function addEvent(node, type, callback)
        {
            if(node.addEventListener)
            {
                node.addEventListener(type, function(e)
                {
                    callback(e, e.target);

                }, false);
            }
            else if(node.attachEvent)
            {
                node.attachEvent('on' + type, function(e)
                {
                    callback(e, e.srcElement);
                });
            }
        }


        //identify whether a field should be validated
        //ie. true if the field is neither readonly nor disabled, 
        //and has either "pattern", "required" or "aria-invalid"
        function shouldBeValidated(field)
        {
            return (
                !(field.getAttribute('readonly') || field.readonly)
                &&
                !(field.getAttribute('disabled') || field.disabled)
                &&
                (
                    field.getAttribute('pattern')
                    ||
                    field.getAttribute('required')
                )
            ); 
        }


        //field testing and validation function
        function instantValidation(field)
        {
            //if the field should be validated
            if(shouldBeValidated(field))
            {
                //the field is invalid if: 
                //it's required but the value is empty 
                //it has a pattern but the (non-empty) value doesn't pass
                var invalid = 
                (
                    (field.getAttribute('required') && !field.value)
                    ||
                    (
                        field.getAttribute('pattern') 
                        && 
                        field.value 
                        && 
                        !new RegExp(field.getAttribute('pattern')).test(field.value)
                    )
                );

                //add or remove the attribute is indicated by 
                //the invalid flag and the current attribute state
                if(!invalid && field.getAttribute('aria-invalid'))
                {
                    field.removeAttribute('aria-invalid');
                }
                else if(invalid && !field.getAttribute('aria-invalid'))
                {
                    field.setAttribute('aria-invalid', 'true');
                }
            }
        }


        //now bind a delegated change event 
        //== THIS FAILS IN INTERNET EXPLORER <= 8 ==//
        //addEvent(document, 'change', function(e, target) 
        //{ 
        //  instantValidation(target); 
        //});


        //now bind a change event to each applicable for field
        var fields = [
            document.getElementsByTagName('input'), 
            document.getElementsByTagName('textarea')
            ];
        for(var a = fields.length, i = 0; i < a; i ++)
        {
            for(var b = fields[i].length, j = 0; j < b; j ++)
            {
                addEvent(fields[i][j], 'change', function(e, target)
                {
                    instantValidation(target);
                });
            }
        }


    })();
    </script>

</body>
</html>
任何帮助(即使是非常简短的解释)都将不胜感激

#1这是一个事件处理程序抽象层。 这一代码段充当事件处理程序,但可跨各种不同的浏览器工作

  • 大多数浏览器使用添加事件处理程序的
    addEventListener
    方式

  • 某些Internet Explorer版本使用
    attachEvent

该功能允许使用两种方式

它让你通过…

  • 。。。要向其添加事件的元素(
    节点
  • 。。。要处理的事件类型(
    类型
  • 。。。事件(
    回调
    )要执行的代码
浏览器事件:

    function addEvent(node, type, callback)
    {
        if(node.addEventListener)
        {
            node.addEventListener(type, function(e)
            {
                callback(e, e.target);

            }, false);
        }
        else if(node.attachEvent)
        {
            node.attachEvent('on' + type, function(e)
            {
                callback(e, e.srcElement);
            });
        }
    }
抽象层:

    function addEvent(node, type, callback)
    {
        if(node.addEventListener)
        {
            node.addEventListener(type, function(e)
            {
                callback(e, e.target);

            }, false);
        }
        else if(node.attachEvent)
        {
            node.attachEvent('on' + type, function(e)
            {
                callback(e, e.srcElement);
            });
        }
    }
浏览器事件包括页面满负荷(
onload
)、点击某物(
onclick
)、更改输入(
onchange
)、光标移动到元素上(
onmouseover
)等

#2如何调用验证
onSubmit
。。。 下面的代码通过每个
输入
文本区域
元素,并使用
onchange
事件向每个元素添加验证。但是您要做的是验证提交上的
onsubmit
,这需要类似的东西,在另一个
addEvent
调用下面:

addEvent("myform","onsubmit", function(){
    //de Go field by field and validate.
    //de If all the fields pass, return true.
    //de If one or more fields fail, return false.
})
如果需要,甚至可以删除
onChange
事件。这是你的选择。这里的主要问题是,您需要确保只验证表单本身内部的字段,您可以查看此答案以了解有关以下内容的更多信息:。。。循环遍历所有元素,并验证上面提到的
addEvent
中的每个元素,该元素必须返回
true
false
,以允许提交表单,或停止提交并显示存在验证错误


请记住作为个人建议。。。在服务器端,您仍然希望执行验证,即使您有客户端验证。浏览器很容易操作,因此可能仍有坏数据发送到服务器。始终,始终执行服务器端验证,而不考虑客户端。

它看起来就像一个跨浏览器函数,将处理程序(
instantValidation
)附加到所有输入和文本区域控件的“更改”或“onchange”事件

我之所以说跨浏览器,是因为存在两种独立的事件订阅方法
attachEvent
适用于较旧的IE浏览器(5-8),而
addEventListener
通常适用于所有现代浏览器


这是一个跨浏览器代码,用于将事件处理程序附加到DOM元素引发的事件上。函数(
addEvent
)具有如下参数:

node
:事件将附加到的DOM节点对象(可通过类似于
getElementById的函数检索)

类型
:事件名称,如
更改
焦点

回调
:引发事件时要调用的函数

此行:
if(node.addEventListener)
检查节点是否具有名为
addEventListener的属性。如果属性存在,则其行为与
true
相同,并且输入
If


检查
addEventListener
,是因为不同的浏览器实现此事件附件功能的方式不同。也就是说,IE9之前的IE版本只使用
attachEvent

我没有完全编写onSubmit处理程序,但我向您展示了这方面的情况,并在下面解释了代码。好问题。欢迎来到StackOverflow。哇!这是一大堆信息;)我会仔细检查你提供的文档,并试一试!非常感谢:)没问题,再一次。。欢迎