2012-02-18 78 views
1

我對JavaScript沒有經驗,而且我一直在嘗試一段時間,以便在用戶單擊提交按鈕時輸入錯誤格式的郵編時,使此表單顯示警告消息。到目前爲止,我所取得的成果都放在了一個驗證所有字段的函數中,我使用名稱來引用函數內部的字段。 (很抱歉,如果我沒有正確縮進)如何使用JavaScript驗證此表單上的郵政編碼?

var g=document.forms["myform"]["postcode"].value; 
if (g==null || g=="") 
{ 
    alert("Please enter your Post CODE"); 
    return false; 
} 
var regPostcode = /^([a-zA-Z]){1}([0-9][0-9]|[0-9]|[a-zA-Z][0-9] 
[a-zA-Z]|[a-zA-Z][0-9][0-9]|[a-zA-Z][0-9]){1}([ ])([0-9][a-zA-z][a-zA-z]){1}$/; 
if(regPostcode.test(postcode) == false) 
{ 
    alert("That Post Code is incorrect"); 
    return false; 
} 

下面是形式IM內部的具體領域使用

<div class=」field_container」><label>Post Code</label><input type=」text」 name="postcode" id="postcode" /></div> 
+1

可能重複[英國郵政編碼正則表達式(綜合)(http://stackoverflow.com/questions/164979/uk-postcode-正則表達式全面) – 2012-02-18 18:47:35

+3

所有國家的郵政編碼格式都不相同。所以沒有統一的正則表達式可以適用於所有郵政編碼。 – 2012-02-18 18:49:50

回答

0

假設你的正則表達式是你的目標是在全國正確的HTML,我倒是嘗試是這樣的:

var g = document.forms["myform"]["postcode"].value; 
var regPostcode = /^([a-zA-Z]){1}([0-9][0-9]|[0-9]|[a-zA-Z][0-9] 
    [a-zA-Z]|[a-zA-Z][0-9][0-9]|[a-zA-Z][0-9]){1}([ ])([0-9][a-zA-z][a-zA-z]){1}$/; 
if (!g) 
{ 
    alert("Please enter your Post CODE"); 
    return false; 
} 
if (!g.match(regPostcode)) 
{ 
    alert("That Post Code is incorrect"); 
    return false; 
} 

正如@Shiplu說,沒有統一的正則表達式,將針對每個國家的郵政代碼工作。你應該確保你想阻止生活在其他國家的人提交表格。

希望這會有所幫助。

0

此外,你應該添加一個簡單的可訪問性增強,像這樣:

<div class="field_container"> 
    <label for="postcode">Post Code</label> <!-- the "for" attribute should match the "id" attribute of the input it corresponds to --> 
    <input type="text" name="postcode" id="postcode" /> 
</div>