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

use*_*810 5 javascript forms validation function handler

我是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>
Run Code Online (Sandbox Code Playgroud)

特别是,以下代码对我来说并不清楚:

    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);
            });
        }
    }
Run Code Online (Sandbox Code Playgroud)

任何帮助(甚至是非常简短的解释)都将受到高度赞赏!

dig*_*ist 2

#1 这是一个事件处理程序抽象层。

代码部分充当事件处理程序,但适用于各种不同的浏览器。

该功能允许使用两种方式。

它让你通过...

  • ...您想要添加事件的元素 ( node)
  • ...您要处理什么类型的事件 ( type)
  • ...您希望事件执行什么代码 ( callback)

浏览器事件: http: //eloquentjavascript.net/chapter13.html

抽象层: http://en.wikipedia.org/wiki/Abstraction_layer

浏览器事件包括页面填满加载 ( onload)、某些内容被单击 ( onclick)、输入被更改 ( onchange)、光标移过元素 ( onmouseover) 等...

http://www.w3schools.com/js/js_htmldom_events.asp

#2 如何调用验证onSubmit......

//now bind a change event to each applicable for field
Run Code Online (Sandbox Code Playgroud)

下面的代码遍历每个inputtextarea元素,并使用事件向每个元素添加验证onchange。但是您想要做的是 validate 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.
})
Run Code Online (Sandbox Code Playgroud)

如果需要,您甚至可以删除这些onChange事件。那是你的选择。这里最主要的是,您需要确保只验证表单本身内部的字段,您可以查看此答案以获取有关以下内容的更多信息:最佳实践:通过 HTML id 或 name 属性访问表单元素?...循环遍历所有元素,并验证addEvent上面提到的每个元素,这些元素必须返回truefalse允许提交表单,或停止提交并显示存在验证错误。

请记住!作为个人建议......在服务器端,即使您有客户端验证,您仍然想要进行验证。浏览器很容易操纵,因此您可能仍然会将错误的数据发送到服务器。无论客户端如何,始终始终进行服务器端验证。