Description
Pre-Checks
- Follow our Code of Conduct.
- Read the Contributing Guidelines.
- Read the docs.
- Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
- Make sure this is a Faker issue and not related to a combination with another package.
- Check that this is a concrete bug. For Q&A open a GitHub Discussion or join our Discord Chat Server.
- The provided reproduction is a minimal reproducible example of the bug.
- I am willing to provide a PR.
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