Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I validate worldwide postal codes in my .NET code

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).

like image 242
Jana Šimurdová Avatar asked Aug 31 '25 06:08

Jana Šimurdová


2 Answers

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");
like image 165
istanishev Avatar answered Sep 02 '25 19:09

istanishev


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

like image 39
Hayim Shimshon Avatar answered Sep 02 '25 20:09

Hayim Shimshon