Postal code validating in Symfony like a pro!

Martin Schindler
4 min readJan 29, 2025

--

The precise verification of postcodes is crucial for applications that process user addresses. One of the most prominent areas of application is certainly the use in an web-based e-commerce system, especially as the quality of the customer master data (for billing and delivery addresses) is not insignificant.

For this reason, I created a Github project called barbieswimcrew/zip-code-validatora few years ago, which is very popular and has now been downloaded well over 1.5 million times.

So it’s about time to tell you about this project and show you how you can use it to ensure valid postcode data in Symfony-based web applications!

Installation

To integrate the barbieswimcrew/zip-code-validator into your project, ensure you have Composer installed. Then, run the following command:

composer require barbieswimcrew/zip-code-validator

This command will add the package to your composer.json and update the composer.lock file accordingly.

Usage

The barbieswimcrew/zip-code-validator is designed to work seamlessly with Symfony's form and validation components. It provides a ZipCode constraint that you can apply to your form fields.

1. Adding the Constraint to a Form Field

When building a form, you can add the ZipCode constraint to a field as follows:

use ZipCodeValidator\Constraints\ZipCode;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;

// ...

$form = $this->createFormBuilder($address)
->add('zipcode', TextType::class, [
'constraints' => [
new ZipCode(['iso' => 'DE']) // Replace 'DE' with the appropriate ISO 3166-1 alpha-2 country code
],
])
->add('save', SubmitType::class, ['label' => 'Submit'])
->getForm();

In this example, the ZipCode constraint validates the zipcode field against the pattern for Germany (DE). Ensure you replace 'DE' with the relevant ISO 3166-1 alpha-2 country code as needed.

2. Using the Constraint as an Attribute (or Annotation)

Alternatively, you can apply the constraint directly in your entity using PHP8 related Attributes:

<?php

use ZipCodeValidator\Constraints\ZipCode;

class Address
{
#[ZipCode(['iso'=>'DE'])
protected $zipCode;

// ...
}

This method is useful when you prefer to define constraints within your entity classes.

Note: Of course, it is also possible to use annotations instead of the attributes available since PHP8. Please have a look at the official documentation of the package on GitHub.

3. Dynamic Country Code Validation

If your form allows users to select a country, you might want to validate the zip code dynamically based on the selected country. You can achieve this by specifying a getter method that returns the country code:

use ZipCodeValidator\Constraints\ZipCode;

class Address
{
#[ZipCode(['getter'=>'getCountry'])
protected $zipCode;

protected $country;

public function getCountry()
{
return $this->country;
}

// ...
}

In this setup, the getCountry method provides the country code for the zip code validation. Ensure that the country property is set appropriately before validation.

To disable that the validator throws an exception, when the zip code pattern is not available for a country, you can set the strict option to FALSE.

use ZipCodeValidator\Constraints\ZipCode;

class Address
{
#[ZipCode(['getter'=>'getCountry', 'strict'=>false])
protected $zipCode;

// ...
}

4. Case Sensitivity in Validation

The validator performs case-sensitive checks by default. To make the validation case-insensitive, set the caseSensitiveCheck option to false:

use ZipCodeValidator\Constraints\ZipCode;

class Address
{
#[ZipCode(['iso'=>'GB', 'caseSensitiveCheck'=>false])
protected $zipCode;

// ...
}

This configuration ensures that the zip code validation does not consider letter casing.

Important Considerations

The validator does not process empty strings or null values. To enforce the presence of a zip code, combine the ZipCode constraint with Symfony's NotBlank or NotNull constraints:

<?php

use Symfony\Component\Validator\Constraints\NotBlank;
use ZipCodeValidator\Constraints\ZipCode;

class Address
{
#[ZipCode(['iso'=>'DE'])
#[NotBlank]
protected $zipCode;

// ...
}

This ensures that the zipCode field is not left empty during validation.

However, it is important to remember that barbieswimcrew/zip-code-validator only verifies whether a zip code follows a valid format for a given country—it does not check whether a specific zip code actually exists. For applications requiring precise address validation, it should be combined with an external postal code database or an API that verifies real addresses.

All regex patterns used for validation can be found in the following file: https://github.com/barbieswimcrew/zip-code-validator/blob/master/src/ZipCodeValidator/Constraints/ZipCodeValidator.php

If you notice that a regex pattern is no longer correct, feel free to create a pull request and don’t forget to add appropriate unit tests to ensure functionality.

Validating postal codes is a crucial aspect of many web applications, especially when handling user addresses in forms and databases. The barbieswimcrew/zip-code-validator package provides a powerful and flexible solution for ensuring that postal codes are correctly formatted according to country-specific rules.

By integrating this package into your Symfony application, you can improve data accuracy, enhance user experience, and prevent incorrect address entries. The ability to dynamically validate zip codes based on user-selected countries, handle missing patterns gracefully, and apply case-insensitive checks makes this package highly versatile.

Overall, the barbieswimcrew/zip-code-validator is a valuable tool for developers looking to implement robust postal code validation in their Symfony applications. With its easy installation and integration, it helps maintain data integrity while offering a seamless user experience.

Feel free to take a look at the package and try it out. I look forward to your feedback and collaboration.

Happy validating!

--

--

Martin Schindler
Martin Schindler

Written by Martin Schindler

Bachelor of Computer Science & Software Architect with a weakness for perfection and the awareness of human imperfection. Passionate mountain biker 🤘

No responses yet