Removing Commerce Address Validation

Commerce 4.1 now takes advantage of Craft 4’s standard address validation. While this should be a step forward for ensuring locale-sensitive address compliance, it’s also a change in behavior that some developers may not want, or may not want in addition to validation they’ve established by other means.

Address validation rules are managed like other Craft models, so you can remove any validation you don’t want by hooking into EVENT_DEFINE_RULES and removing undesired validation rules from the rules array.

If we wanted to remove the required country code, 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] === 'countryCode' && $rule[1] === 'required') {
                unset($event->rules[$key]);
            }
        }
    }
);

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]);
            }
        }
    }
);

Applies to Craft Commerce 4.