Skip to content

Commit

Permalink
Allow turning off postal code validation in AddressFormatConstraint.
Browse files Browse the repository at this point in the history
Fixes #207.
  • Loading branch information
bojanz committed Jan 9, 2024
1 parent 65444d0 commit 74edab2
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 1 deletion.
2 changes: 2 additions & 0 deletions src/Validator/Constraints/AddressFormatConstraint.php
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
}

0 comments on commit 74edab2

Please sign in to comment.