2013-09-25 55 views
18

我正在使用jQuery Validation plugin驗證我的表單。如何使用jQuery驗證插件驗證美國郵政編碼

我想驗證郵政編碼按照美國郵政編碼格式: -

> 12345 
> 12345-6789 
> 12345 6789 

按我CURENT代碼的驗證郵編應該是最大的5和所有的數字。

請參閱下面的代碼:

<script src="~/Scripts/js/jquery.validate.js"></script> 

<script> 

    $().ready(function() { 

     // validate signup form on keyup and submit 
     $("#locationSetup").validate({ 
      rules: { 
       'Address.AddressStreet': "required", 
       'Address.City': "required", 
       'Address.State.Country.CountryIsoCode': "required", 
       'Address.State.SubnationalIsoCode': "required", 
       'Address.PostalCode': { 
        required: true, 
        minlength: 5, 
        maxlength: 5, 
        digits: true 
       } 
      }, 
      messages: { 
       'Address.AddressStreet': "Please enter your Street Address!", 
       'Address.City': "Please select your City!", 
       'Address.State.Country.CountryIsoCode': "Please select your Country!", 
       'Address.State.SubnationalIsoCode': "Please select your State!", 
       'Address.PostalCode': { 
        required: "Please enter your Postal Code!", 
        minlength: "Your Postal Code must be 5 numbers!", 
        maxlength: "Your Postal Code must be 5 numbers!", 
        digits: "Your Postal Code must be 5 numbers!" 
       } 
      } 
     }); 

    }); 
</script> 

@using (Html.BeginForm(Model.Step.ToString(), "Provision", FormMethod.Post, new Dictionary<string, object> { { "id", "locationSetup" } })) 

<table width="100%" id="locInfo"> 
      <colgroup> 
       <col width="30%" /> 
       <col /> 
      </colgroup> 
      <tr> 
       <th><label>@AddressResource.COUNTRY_LABEL_TEXT:</label> <span class="redtext">(Required)</span></th> 
       <td> 
        @* @Html.HiddenFor(m => m.Address.State.Country.CountryIsoCode)*@ 
        @Html.DropDownListFor(m => m.Address.State.Country.CountryIsoCode, ProvisioningHubProxy.GetCountriesList(), 
           htmlAttributes: new { @id = "Countries", @name = "Countries" }) 
       </td> 
      </tr> 
      <tr> 
       <th> <label>@AddressResource.STATES_LABEL_TEXT:</label><span class="redtext">(Required)</span></th> 
       <td> @Html.DropDownListFor(m => m.Address.State.SubnationalIsoCode, ProvisioningHubProxy.GetStatesList(), 
           htmlAttributes: new { @id = "States", @name = "States" })</td> 
      </tr> 
      <tr> 
       <th><label>@AddressResource.CITY_LABEL_LABEL_TEXT:</label><span class="redtext">(Required)</span></th> 
       <td> @Html.TextBoxFor(m => m.Address.City, htmlAttributes: new { @name = "City", @id = "City" })</td> 
      </tr> 
      <tr> 
       <th> <label>@AddressResource.STREET_NAME_LABEL_TEXT:</label><span class="redtext">(Required)</span></th> 
       <td>@Html.TextBoxFor(m => m.Address.AddressStreet, htmlAttributes: new { @name = "StreetName", @id = "StreetName" })</td> 
      </tr> 
      <tr> 
       <th><label>@AddressResource.US_POSTAL_CODE_LABEL_TEXT:</label><span class="redtext">(Required)</span></th> 
       <td>@Html.TextBoxFor(m => m.Address.PostalCode, htmlAttributes: new { @name = "ZipCode", @id = "ZipCode", @required = "required" })</td> 
      </tr> 
     </table> 

}

請建議。

+0

[jQuery validation plugin:只接受美國,加拿大和墨西哥的郵政編碼?](http://stackoverflow.com/questions/15794913/jquery-validation-plugin-accept-only-us-canada-and -mexic-zip-code) – Blazemonger

+5

[additional-methods.js'文件]裏面已經有一條叫做'zipcodeUS'的規則(http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional -methods.js)。 – Sparky

回答

28

添加自定義的驗證:

jQuery.validator.addMethod("zipcode", function(value, element) { 
    return this.optional(element) || /^\d{5}(?:-\d{4})?$/.test(value); 
}, "Please provide a valid zipcode."); 

_IF要接受空間郵政編碼之間,使用/^\d{5}(?:[\s-]\d{4})?$/的模式來代替。

然後在選項指定:

rules: { 
    ... 
    'Address.PostalCode': { 
    ... 
    zipcode: true, 
    ... 
    }, 
    ... 
} 

注意,擴展庫additional-methods.jszipcodeUS驗證以及(但除非你使用任何其他的人的,可能沒有什麼意義,包括它)。 ( - )和四(4)附加的號碼


根據規範,適當格式化的郵遞區號由連字符包括五個(5)號碼或五(5)號碼跟隨器。一個空間不應該在技術上是可以接受的,但我會提供模式無論如何。

+0

謝謝!多麼簡單的解決方案..它的工作! – UID

+0

正則表達式不能正確處理空間格式:12345 6789 – Blago

+0

@Blago:已更新答案以適應。 –

2

可以定義一個自定義的驗證:

jQuery.validator.addMethod('zipcode', function(value, element) { 
    return this.optional(element) || !!value.trim().match(/^\d{5}(?:[-\s]\d{4})?$/); 
}, 'Invalid zip code'); 

然後使用它像這樣

<input class="zipcode"/> 
15

只需提供the additional-methods.js file和使用zipcodeUS規則。

$("#locationSetup").validate({ 
    rules: { 
     // rules, 
     'Address.PostalCode': { 
      required: true, 
      zipcodeUS: true // <-- use it like this 
     } 
    }, 
.... 

如果你不希望包括additional-methods.js文件,你可以在下面的方法複製到你的代碼...

jQuery.validator.addMethod("zipcodeUS", function(value, element) { 
    return this.optional(element) || /\d{5}-\d{4}$|^\d{5}$/.test(value) 
}, "The specified US ZIP Code is invalid"); 
+0

,如果我嘗試這個,它會給我錯誤 TypeError:jQuery.validator未定義。 你能告訴我我在這裏錯過了什麼嗎? – ehp

+0

@ehp,錯誤告訴你'validator'沒有被定義。它只是意味着你沒有正確包含jQuery驗證插件。 – Sparky

+0

只是一個說明。如果您確實使用additional-methods.js,請確保獲得與您正在使用的驗證插件版本相對應的版本。這裏的文件是1.11.1,此時的最新版本是1.12.0。 1.11給出了1.12的錯誤。 –

1

郵編驗證程序是額外的,methods.js提供但是如果你打算讓表格在美國以外的其他國家失效,我會質疑你爲什麼要求提供國家信息?請記住,只有約5%的世界人口使用美國郵政編碼。我建議你讓你的郵編驗證程序依賴於用戶實際選擇的國家。