簡體   English   中英

JavaScript表單驗證:了解函數調用

[英]JavaScript Form Validation: understanding function call

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

特別是,以下代碼對我而言還不是很清楚:

    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);
            });
        }
    }

任何幫助(甚至是一個簡短的解釋)將不勝感激!

#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

下面的代碼遍歷每個inputtextarea元素,並使用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事件。 那是你的選擇。 這里的主要問題是,您需要確保僅驗證表單本身內的字段,您可以查看此答案以獲取有關以下內容的更多信息: 最佳實踐:通過HTML id或name屬性訪問表單元素? ...遍歷所有元素,並驗證我上面提到的addEvent每個元素,這些元素必須返回truefalse以允許提交表單,或者停止提交並顯示存在驗證錯誤。

請記住! 作為個人建議...在服務器端,即使您已進行客戶端驗證,您仍要進行驗證。 瀏覽器易於操作,因此您仍然可能有不良數據發送到服務器。 始終,無論客戶端如何, 始終進行服務器端驗證。

它看起來像一個跨瀏覽器功能,它將處理程序( instantValidation )附加到所有輸入和textarea控件的“ change”或“ onchange”事件。

我說跨瀏覽器是因為存在兩種單獨的事件訂閱方法。 attachEvent用於較舊的IE瀏覽器(5-8),而addEventListener通常用於所有現代瀏覽器。

這個addEvent函數檢查所述函數的存在並使用可用的任何東西,從而優先考慮“現代”方式。

這是跨瀏覽器的代碼,用於將事件處理程序附加到DOM元素引發的事件。 函數( addEvent )具有如下參數:

node :事件將附加到的DOM節點對象(可通過類似getElementById的函數檢索)

type :事件名稱,例如changefocus等。

callback :引發事件時調用的函數。

這行代碼: if(node.addEventListener)檢查節點是否具有稱為addEventListener的屬性。 如果該屬性存在,則其行為與true相同,並輸入了if塊。

因為不同的瀏覽器以不同的方式實現此事件附件功能,所以完成了對addEventListener的檢查。 即,IE9之前的IE版本僅使用attachEvent

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM