2017-09-09 68 views
0

我在使用Javascript表單驗證時遇到問題。我不知道如何使用具有驗證規則的外部.js腳本,並將它們插入到html文件中並使其工作。Javascript表單驗證。如何使用外部.js驗證腳本

我在頭部分鏈接的腳本是這樣的:

這是什麼在.js文件驗證腳本

function IsValid4DigitZip(str) 
    if (str+"" == "undefined" || str+"" == "null" || str+"" == "") 
     return false; 

    var isValid = true; 

    str += ""; 

    if (IsBlank(str) || (str.length != 4) || !IsInt(str, false)) 
     isValid = false; 

    return isValid; 
} 

我試着將它插入部分如下

function IsValid4DigitZip(document.orderbooks.Postcode) { 

    if (document.orderbooks.Postcode.value+"" == "undefined" || document.orderbooks.Postcode.value+"" == "null" || document.orderbooks.Postcode.value+"" == "") 
     alert("Invalid Postcode !") 
     return false; 

    var isValid = true; 

    document.orderbooks.Postcode += ""; 


    if (IsBlank(document.orderbooks.Postcode) || (document.orderbooks.Postcodestr.length != 4) || !IsInt(document.orderbooks.Postcode, false)) 
     alert("Invalid Postcode!") 
     isValid = false; 

    return isValid; 
} 

orderbooks是我的表單名稱在我的HTML和Postcode是我想驗證使用JavaScript的名稱屬性..

我在做什麼錯?

+0

您不修改現有功能 - 您需要將數據傳入並捕獲返回以進一步處理它。 [這是一些基本的閱讀材料](https://www.w3schools.com/js/js_function_parameters.asp)。你也提到你的HTML,但它似乎並沒有被添加到這個問題中,使得它更難回答。 –

+0

我不明白:(對不起,我是新來的,你能告訴我和例子嗎?我如何傳遞數據並捕獲它? – c0nfus3d

回答

0

既然你已經有了郵政編碼驗證功能,你只需要調用它的表單數據。

if (IsValid4DigitZip(document.orderbooks.Postcode.value)) { 
    // Zip code is valid 
} else { 
    // Zip code is invalid 
} 
+0

但是等等!還有更多!'orderbooks是我的表單名稱在我的html和Postcode是名稱屬性是讓我意識到這個「問題」是多麼廣泛的部分,以及如何回答它是不可能的,沒有解釋大量的JS和HTML。 –

+0

我剛剛上傳了我的HTML,你可以看看和回到我身邊? – c0nfus3d

+0

看不到任何html – GKK