8000 Invalid zip/postal codes when using locale en_GB · Issue #2390 · faker-js/faker · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
Invalid zip/postal codes when using locale en_GB #2390
Open
@mikeybinns

Description

@mikeybinns

Pre-Checks

Describe the bug

Very closely related to #1416 but for a different locale, so I though a new ticket would be appropriate.

Great Britain post codes also have some specific rules which means that some of the generated postcodes are invalid.

I have a REGEX string for validating if a GB post code is valid, so I'm sharing it here as hopefully it will help, even if only with automated testing. This regex is created based on this gov.uk document

/^([A-Z]{1,2}[0-9]{1,2}|[A-Z]{1,2}[0-9]{1}[A-Z]{1})([0-9]{1}[ABDEFGHJLNPQRSTUWXYZ]{2})$/gi,

I think the biggest tripping block for Faker here is that the final two letters cannot be C I K M O V.

For those who come across this issue, here's a workaround to get you going in modern TypeScript:

/**
 * Generate a valid UK postcode using faker.
 * 
 * Faker's implementation is too generic to work with strict 
 * post code validators, so we must check the values returned 
 * to see if they are valid
 * @see https://github.com/faker-js/faker/issues/2390
 * 
 * @returns A promise which resolves to a valid UK postcode
 */
async function generatePostCode() {
  return new Promise<string>((resolve) => {
    let postcode = "";
    while (
      postcode
        // Remove all characters except numbers and letters (including spaces as spaces are optional)
        .replaceAll(/[^A-Z0-9]/gi, "")
        // Check value against REGEX
        .match(
          /^([A-Z]{1,2}[0-9]{1,2}|[A-Z]{1,2}[0-9]{1}[A-Z]{1})([0-9]{1}[ABDEFGHJLNPQRSTUWXYZ]{2})$/gi,
        )
    ) {
      postcode = faker.location.zipCode();
    }
    resolve(postcode);
  });
}

Minimal reproduction code

import { fakerEN_GB as faker } from "@faker-js/faker";
console.log(faker.location.zipCode());

Additional Context

In case the link breaks, here is that gov.uk document I mentioned.
Appendix_C_ILR_2017_to_2018_v1_Published_28April17.pdf

Environment Info

System:
  OS: macOS 13.5.1
  CPU: (8) arm64 Apple M1
  Memory: 480.53 MB / 16.00 GB
  Shell: 5.9 - /bin/zsh
Binaries:
  Node: 18.17.1 - ~/.nvm/versions/node/v18.17.1/bin/node
  npm: 9.6.7 - ~/.nvm/versions/node/v18.17.1/bin/npm
Browsers:
  Chrome: 116.0.5845.179
  Safari: 16.6
npmPackages:
  @faker-js/faker: ^8.0.1 => 8.0.2

Which module system do you use?

  • CJS
  • ESM

Used Package Manager

npm

Metadata

Metadata

Assignees

Labels

c: bugSomething isn't workingc: localePermutes locale definitionshas workaroundWorkaround provided or linkedm: locationSomething is referring to the location modulep: 1-normalNothing urgent

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions

    0