I am looking for a way to validate worldwide postal codes in my .NET project, and I don't really want to come up and maintain regular expressions for the whole world.
Preferably I would want to pull in a dependency to a library or in the worst case use some web based service (but that would really be a last resort).
Check out PostalCodes.Net package on github.
It support most countries and has a good interface. Here is an example:
var country = CountryFactory.Instance.CreateCountry("PL");
var postalCode = PostalCodeFactory.Instance.CreatePostalCode(country, "44-100");
For Anyone looking As of .NET 8.
I’ve released a C# port (rebuilt) of the RestCountries (JAVA), fully compatible with the original JSON and now compatible with Dependency Injection (DI) for ASP.NET.
This package will give you access to Phone Prefixes, translated names for the countries their ids and more..
For the OpenCodeDev.RestCountries.Data 3.1, it includes postal code regex patterns and if the country requires a postal or not which is very useful for international validation.
OpenCodeDev.RestCountries .NET 6.0, .NET 8.0 & .NET 9.0
OpenCodeDev.RestCountries.Data for the Countries DATA.
using OpenCodeDev.RestCountries.Embedded;
using OpenCodeDev.RestCountries.Data;
IRestCountries restCountries = new RestCountries(RestCountriesEmbed.GetVersion());
var countries = restCountries.GetAll();
var firstCountry = countries.First();
if (restCountries.IsValidCCA2PostalCode("ca", "H1T2S2"))
Console.WriteLine($"Valid");
else
Console.WriteLine($"Not Valid");
Documentation Github
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With