1

Trying to allow either UK postcode (GF433ED) or European postcode (12345) return true or false but the below code always returns false:

 function valid_postcode(postcode) {
     postcode = postcode.replace(/\s/g, "");
     alert(postcode);
     var regex = /^[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}|^[0-9]{5}$/;
     return regex.test(postcode); 
 }

Any help would be greatly appreciated.

Thanks

Max
  • 27
  • 6
  • Please note your UK postcode regex is not complete. See here for the one provided by the UK government: `([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))\s?[0-9][A-Za-z]{2})` https://stackoverflow.com/questions/164979/uk-postcode-regex-comprehensive – Rory McCrossan Aug 07 '17 at 15:32

2 Answers2

1

Use \s* for allowing an optional space.

/[A-z]{1,2}[0-9]{1,2}\s*[0-9][A-Z]{2}/i
Chandra Kumar
  • 4,127
  • 1
  • 17
  • 25
  • The regex is not correct because [`[A-z]` matches more than letters](https://stackoverflow.com/questions/29771901/why-is-this-regex-allowing-a-caret/29771926#29771926). Moreover, anchors are likely to be required since it seems the codes need to be validated as whole strings. – Wiktor Stribiżew Aug 07 '17 at 16:04
0

Thanks everyone it was all a bit of both (forgot to post answer)

See working regex:

/^[A-z]{1,2}[0-9]{1,2}\s*[0-9][A-z]{2}$|^[0-9]{5}$/

Max
  • 27
  • 6