0

I am trying to validate UK and overseas postcode. The UK postcode validation is working but not the overseas. Is there any specific regex for the overseas or can be done with the regex I have used in the jsfiddle code.

I have gone through this post - https://stackoverflow.com/a/164994/2455424 and tried to use the following regex but didn't work.

^(GIR ?0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]([0-9ABEHMNPRV-Y])?)|[0-9][A-HJKPS-UW]) ?[0-9][ABD-HJLNP-UW-Z]{2})$

So I have commented out that line.

Jquery code -

 $('#testForm').on('submit', function() {
   var zip = $('#zip').val();
   zip = zip.replace(/\s/g, "");
   var regex = /[A-Z]{1,2}[0-9][0-9A-Z]?\s?[0-9][A-Z]{2}/gi;
   //var regex = ^(GIR ?0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]([0-9ABEHMNPRV-Y])?)|[0-9][A-HJKPS-UW]) ?[0-9][ABD-HJLNP-UW-Z]{2})$;
   var resultzip = regex.test(zip);
   if (false === resultzip) {
     alert('The postcode is not valid.');
     return false;
   }
 });

Demo -- https://jsfiddle.net/squidraj/q4ouLns7/5/

Any help is highly appreciated.

Community
  • 1
  • 1
Prithviraj Mitra
  • 11,002
  • 13
  • 58
  • 99

2 Answers2

0

Please try this one

var regex = /(((^[BEGLMNS][1-9]\d?) | (^W[2-9] ) | ( ^( A[BL] | B[ABDHLNRST] | C[ABFHMORTVW] | D[ADEGHLNTY] | E[HNX] | F[KY] | G[LUY] | H[ADGPRSUX] | I[GMPV] | JE | K[ATWY] | L[ADELNSU] | M[EKL] | N[EGNPRW] | O[LX] | P[AEHLOR] | R[GHM] | S[AEGKL-PRSTWY] | T[ADFNQRSW] | UB | W[ADFNRSV] | YO | ZE ) \d\d?) | (^W1[A-HJKSTUW0-9]) | (( (^WC[1-2]) | (^EC[1-4]) | (^SW1) ) [ABEHMNPRVWXY] ) ) (\s*)? ([0-9][ABD-HJLNP-UW-Z]{2})) | (^GIR\s?0AA)/;
Jamiec
  • 133,658
  • 13
  • 134
  • 193
Ritwika Das
  • 189
  • 5
0

Postal codes formats around the world vary a lot, and sometimes a format can look similar to another countries with subtle differences, such as only using certain characters in certain positions.

Frank's compulsive guide to addressing will contain more information about address and postal code formats than you will ever need.

Also even with a RegEx for every country, RegEx only ever tells you if the postcode "looks" right. To validation properly you need check it exists in the local postal authority's database. In the UK this would be Royal Mail's PAF database.

Stephen Keable
  • 299
  • 3
  • 15