haterapps / fake-data

Fake Data - A form filler you won't hate
39 stars 2 forks source link

Uk locale #31

Closed toomanylogins closed 3 months ago

toomanylogins commented 8 months ago

Hello, Pro user here. Is there a setting for locale ? for example postcode not zip etc ? If not any examples of custom generators would be useful. Thanks

haterapps commented 7 months ago

Hello,

Unfortunately, it seems that the faker.js library, which the extension uses for generating the fake data does not contain UK postcodes.

You could use a custom js code to generate these postal postcodes. Here is a quick example that I've found over the internet:

return (function generateUKPostcode() {
  // Define the postcode format
  const postcodeFormat = /^(?:(?:(?:[A-Z][0-9]{1,2})|(?:[A-Z][A-HJ-Y][0-9]{1,2})|(?:[A-Z][0-9][A-Z]))\s?[0-9][ABD-HJLNP-UW-Z]{2})$/;

  // Generate a random outward code (first part of the postcode)
  const outwardCode = String.fromCharCode(Math.floor(Math.random() * 26) + 65) +
    Math.floor(Math.random() * 10) +
    (Math.random() > 0.5 ? Math.floor(Math.random() * 10) : '') +
    Math.floor(Math.random() * 10);

  // Generate a random inward code (second part of the postcode)
  const inwardCode = Math.floor(Math.random() * 10) +
    String.fromCharCode(Math.floor(Math.random() * 26) + 65) +
    String.fromCharCode(Math.floor(Math.random() * 26) + 65);

  // Combine outward and inward codes to form the complete postcode
  const postcode = `${outwardCode} ${inwardCode}`;

  // Check if the generated postcode matches the UK postcode format
  if (postcodeFormat.test(postcode)) {
    return postcode;
  } else {
    // If not valid, recursively call the function until a valid postcode is generated
    return generateUKPostcode();
  }
})()

I'm not familiar with UK postcodes, so I can't tell how correct are they, but it could be a good starting point if you want to modify the code. Also, keep in mind that these are most probably not real postcodes that will pass a real address validation.