Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

To validate canadian postal code string using regex, use /^[ABCEGHJ-NPRSTVXY]\d[ABCEGHJ-NPRSTV-Z][ -]?\d[ABCEGHJ-NPRSTV-Z]\d$/i it will handle canadian postal code.

Let’s see short example of javascript regex for canadian postal code.

const regex = /^[ABCEGHJ-NPRSTVXY]\d[ABCEGHJ-NPRSTV-Z][ -]?\d[ABCEGHJ-NPRSTV-Z]\d$/i;
console.log(regex.test("h2t-1b8"))

Today, I’m going to show you How do I check value contain canadian postal code in javascript, as above mentioned, I’m going to use the above-mentioned regex with test() method.

Let’s start today’s tutorial how do you check canadian postal code in javascript using regex?

Here, I will show validate canadian postal code in javascript and typescript.

Javascript regex for canadian postal code example

Here, we will create common validate function where we will validate param should canadian postal code.

function validate(param){
  const regex = /^[ABCEGHJ-NPRSTVXY]\d[ABCEGHJ-NPRSTV-Z][ -]?\d[ABCEGHJ-NPRSTV-Z]\d$/i;
  return regex.test(param);
}

// validate empty string
console.log(validate(""))
// false

// validate postal code with Hyphen
console.log(validate("h2t-1b8"))
// true

// validate canadian postal code with space
console.log(validate("h2t 1b8"))
// true

// validate canadian postal code
console.log(validate("h2t1b8"))
// true

// validate leading Z
console.log(validate("Z2T 1B8"))
// false

// validate contains O
console.log(validate("H2T 1O3"))
// false

Output

Typescript regex for canadian postal code example

Same like javascript, we will create a function and call it with diffrent parameters.

function validate(param: string){
  const regex = /^[ABCEGHJ-NPRSTVXY]\d[ABCEGHJ-NPRSTV-Z][ -]?\d[ABCEGHJ-NPRSTV-Z]\d$/i;
  return regex.test(param);
}

// validate empty string
console.log(validate(""))
// false

// validate postal code with Hyphen
console.log(validate("h2t-1b8"))
// true

// validate canadian postal code with space
console.log(validate("h2t 1b8"))
// true

// validate canadian postal code
console.log(validate("h2t1b8"))
// true

// validate leading Z
console.log(validate("Z2T 1B8"))
// false

// validate contains O
console.log(validate("H2T 1O3"))
// false

Output

I hope it helps you, All the best đź‘Ť.