Removing Commerce Address Validation

In Commerce 4, address storage and validation was moved into Craft itself. While this provides a globally-aware address solution that is consistent across the Craft ecosystem, it’s a behavioral departure that some Commerce projects may not want—the new address system may enforce additional validation, on top of whatever custom rules a developer may have configured.

Need a refresher on working with events? Check out our Using Events in a Custom Module article, or visit the Events page in the extension documentation.

Address validation rules are now are managed like other Craft models—use the craft\elements\Address::EVENT_DEFINE_RULES event to remove any rules you don’t want from the event’s rules array.

If we wanted to make the Postal Code field optional, for example, we could do it like this:

use craft\elements\Address;
use yii\base\Event;

Event::on(
    Address::class, 
    Address::EVENT_DEFINE_RULES, 
    static function($event) {
        foreach ($event->rules as $key => $rule) {
            if ($rule[0] === 'postalCode' && $rule[1] === 'required') {
                unset($event->rules[$key]);
            }
        }
    }
);

Validation rules aren’t named when they’re added, so the only way to remove them is by looking at the attributes and settings themselves.

The rules that apply to a given address depend on its country, so the best way to remove all validation and be consistent with earlier Commerce versions is to remove all possibly-required address fields:

use craft\elements\Address;
use yii\base\Event;

Event::on(
    Address::class, 
    Address::EVENT_DEFINE_RULES, 
    static function($event) {
        foreach ($event->rules as $key => $rule) {
            if (in_array($rule[0], [
                'countryCode',
                'administrativeArea',
                'locality',
                'dependentLocality',
                'postalCode',
                'sortingCode',
                'addressLine1',
                'addressLine2',
            ]) && $rule[1] === 'required') {
                unset($event->rules[$key]);
            }
        }
    }
);

Keep in mind that by making some fields optional (like countryCode), you may impact Craft (and therefore your customers’) ability to accurately provide billing and shipping information!

Applies to Craft CMS 5, Craft CMS 4, Craft Commerce 5, and Craft Commerce 4.