Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate Canadian Postal Code Regex

I have written a JavaScript to validate Canadian Postal Codes using regex.

However, it does not seem to be working:

JavaScript

If statement:

if (myform.zip.value == "" || myform.zip.value == null || myform.zip.value == "Postal Code" || myform.zip.value.length < 12 ) {
    alert("Please fill in field Postal Code. You should only enter 7 characters");
    myform.zip.focus();
    return false;
}

Function:

function okNumber(myform) {
  var regex = /^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$/;
  if (regex.test(myform.zip.value) == false) {
    alert("Input Valid Postal Code");
    myform.zip.focus();
    return false;
  }

  return true;
}

Problem

It doesn't work at all, although code is executing. When I run it, I get:

Please fill in field Postal Code. You should only enter 7 characters

An example valid postal code would be T2X 1V4.

like image 335
Alex Block Avatar asked Jun 22 '12 03:06

Alex Block


People also ask

How are Canadian zip codes formatted?

The postal code is a six-character uniformly structured, alphanumeric code in the form “ANA NAN” where “A” is an alphabetic character and “N” is a numeric character. Two segments make up a postal code: Forward Sortation Area (FSA) and Local Delivery Unit (LDU).

What is valid post code format?

The postal code is composed of 3 sections. The first section is a region code consisting of an alphabet and an alphanumeric character. The second section is a 3-4 digit area code. The third section is an optional 4-digit code identifying the exact address.

How postal codes work in Canada?

Canada Post defines a postal code as follows: A six-character alphanumeric combination (ANA NAN) assigned to one or more postal addresses. The postal code is an integral part of every postal address in Canada and is required for the mechanised processing of mail.


1 Answers

A regex approach can validate the format of a Canadian postcode, but it's not sufficient to guarantee that the postcode actually exists.

For example: A9A 0A0 looks like a valid Canadian postcode, but the forward sortation area A9A doesn't actually exist.

Are you sure you wouldn't rather do some kind of lookup against an official list of postcodes?

like image 150
Li-aung Yip Avatar answered Oct 06 '22 23:10

Li-aung Yip