2013-09-25 76 views
18

Tôi đang sử dụng jQuery Validation plugin để xác thực biểu mẫu của mình.Cách xác thực mã ZIP của Hoa Kỳ bằng cách sử dụng plugin jQuery Validation

Tôi muốn để xác thực mã zip theo định dạng Mỹ ZIPCODE: -

> 12345 
> 12345-6789 
> 12345 6789 

Như mỗi mã curent của tôi nó chứng thực mã bưu điện nên tối đa 5 và tất cả các số.

Xin xem đoạn code dưới đây:

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

}

Xin gợi ý.

+0

bản sao có thể có của [Plugin xác thực jQuery: chỉ chấp nhận mã zip của Hoa Kỳ, Canada và Mexic?] (Http://stackoverflow.com/questions/15794913/jquery-validation-plugin-accept-only-us-canada-and -mexic-zip-code) – Blazemonger

+5

Đã có một quy tắc được gọi là 'zipcodeUS' bên trong [tệp' additional-methods.js'] (http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional -methods.js). – Sparky

Trả lời

28

Thêm một validator tùy chỉnh:

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

_Nếu bạn muốn chấp nhận không gian giữa mã bưu điện, sử dụng /^\d{5}(?:[\s-]\d{4})?$/ cho mô hình thay thế.

sau đó xác định nó trong các tùy chọn của bạn:

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

Lưu ý rằng thư viện mở rộng additional-methods.js có một validator zipcodeUS cũng như (nhưng trừ khi bạn đang sử dụng bất kỳ của những người khác, nó có thể không có ý nghĩa bao gồm nó).


Theo spec, mã zip định dạng đúng bao gồm năm (5) số hoặc năm (5) số đi theo bởi một dấu gạch ngang (-) và bốn (4) số bổ sung. Một không gian không nên về mặt kỹ thuật có thể chấp nhận được, nhưng tôi sẽ cung cấp mẫu bất kể.

+0

Cảm ơn !! những gì một giải pháp đơn giản .. nó đã làm việc !!! – UID

+0

Regex không xử lý đúng định dạng không gian: 12345 6789 – Blago

+0

@Blago: Đã cập nhật câu trả lời cho phù hợp. –

2

Bạn có thể định nghĩa một validator tùy chỉnh:

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

Sau đó sử dụng nó như thế này

<input class="zipcode"/> 
15

Chỉ cần đính kèm the additional-methods.js file và sử dụng các quy tắc zipcodeUS.

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

Nếu bạn không muốn bao gồm các tập tin additional-methods.js, bạn có thể sao chép các phương pháp sau đây vào mã của bạn ...

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

, nếu tôi thử điều này, nó cho tôi lỗi TypeError: jQuery.validator không được xác định. Bạn có thể cho tôi biết những gì thực sự tôi đang thiếu ở đây. – ehp

+0

@ehp, Lỗi này cho bạn biết rằng 'trình xác nhận hợp lệ' không được xác định. Nó chỉ đơn giản có nghĩa là bạn đã không bao gồm đúng plugin jQuery Validation. – Sparky

+0

Chỉ cần ghi chú. Nếu bạn sử dụng phương thức bổ sung-phương thức.js, hãy đảm bảo nhận phiên bản tương ứng với phiên bản của plugin xác thực bạn đang sử dụng. Tệp tại đây là 1.11.1 và tệp mới nhất tại thời điểm này là 1.12.0. 1.11 đã đưa ra lỗi với 1.12. –

1

thói quen xác nhận Zip code đang cung cấp trong thêm-methods.js nhưng tôi sẽ hỏi tại sao bạn yêu cầu thông tin quốc gia nếu bạn sẽ làm mất hiệu lực biểu mẫu cho bất kỳ quốc gia nào khác ngoài Hoa Kỳ? Hãy nhớ rằng chỉ có khoảng 5% dân số thế giới sử dụng mã zip của Hoa Kỳ. Tôi sẽ khuyên bạn nên làm cho bạn thói quen xác nhận mã bưu chính phụ thuộc vào quốc gia thực sự được chọn bởi người dùng.