From 74edab28044ef49c66720030ae2ef4943591981a Mon Sep 17 00:00:00 2001 From: Bojan Zivanovic Date: Tue, 9 Jan 2024 13:03:19 +0100 Subject: [PATCH] Allow turning off postal code validation in AddressFormatConstraint. Fixes #207. --- .../Constraints/AddressFormatConstraint.php | 2 ++ .../AddressFormatConstraintValidator.php | 2 +- .../AddressFormatConstraintValidatorTest.php | 20 +++++++++++++++++++ 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/Validator/Constraints/AddressFormatConstraint.php b/src/Validator/Constraints/AddressFormatConstraint.php index 2e050ce9..04a82042 100644 --- a/src/Validator/Constraints/AddressFormatConstraint.php +++ b/src/Validator/Constraints/AddressFormatConstraint.php @@ -16,6 +16,8 @@ class AddressFormatConstraint extends Constraint { public ?FieldOverrides $fieldOverrides = null; + public bool $validatePostalCode = true; + public string $blankMessage = 'This value should be blank'; public string $notBlankMessage = 'This value should not be blank'; diff --git a/src/Validator/Constraints/AddressFormatConstraintValidator.php b/src/Validator/Constraints/AddressFormatConstraintValidator.php index 624328a9..8d166c21 100644 --- a/src/Validator/Constraints/AddressFormatConstraintValidator.php +++ b/src/Validator/Constraints/AddressFormatConstraintValidator.php @@ -72,7 +72,7 @@ public function validate(mixed $value, Constraint $constraint): void // Validate subdivisions and the postal code. $subdivisions = $this->validateSubdivisions($values, $addressFormat, $constraint); - if (in_array(AddressField::POSTAL_CODE, $usedFields)) { + if (in_array(AddressField::POSTAL_CODE, $usedFields) && $constraint->validatePostalCode) { $this->validatePostalCode($address->getPostalCode(), $subdivisions, $addressFormat, $constraint); } } diff --git a/tests/Validator/Constraints/AddressFormatConstraintValidatorTest.php b/tests/Validator/Constraints/AddressFormatConstraintValidatorTest.php index e098af0c..1591042d 100644 --- a/tests/Validator/Constraints/AddressFormatConstraintValidatorTest.php +++ b/tests/Validator/Constraints/AddressFormatConstraintValidatorTest.php @@ -489,4 +489,24 @@ public function testHiddenSubdivisionField(): void ->setInvalidValue('INVALID') ->assertRaised(); } + + /** + * @covers \CommerceGuys\Addressing\Validator\Constraints\AddressFormatConstraintValidator + */ + public function testNoPostalCodeValidation(): void + { + // Confirm that postal code validation is skipped. + $this->constraint->validatePostalCode = false; + $address = new Address(); + $address = $address + ->withCountryCode('CN') + ->withAdministrativeArea('BJ') + ->withLocality('Xicheng Qu') + ->withAddressLine1('Yitiao Lu') + ->withGivenName('John') + ->withFamilyName('Smith') + ->withPostalCode('INVALID'); + $this->validator->validate($address, $this->constraint); + $this->assertNoViolation(); + } }