Automattic\WooCommerce\Internal\Utilities

PostcodeValidation::validate │ public static │ WC 1.0

Validate a postcode if a shared rule exists for its country.

Method of the class: PostcodeValidation{}

No Hooks.

Returns

bool|null. Whether the postcode is valid, or null when no usable rule exists.

Usage

$result = PostcodeValidation::validate( $postcode, $country ): ?bool;
$postcode(string) (required)
Postcode to validate.
$country(string) (required)
Country code.

PostcodeValidation::validate() code WC 11.2.1

public static function validate( string $postcode, string $country ): ?bool {
	$rules = self::get_rules();
	if ( ! isset( $rules[ $country ] ) ) {
		return null;
	}

	$rule = $rules[ $country ];
	if ( isset( $rule['normalization'] ) ) {
		switch ( $rule['normalization'] ) {
			case 'removeSpaces':
				$postcode = str_replace( ' ', '', $postcode );
				break;
			case 'removeSpacesAndHyphens':
				$postcode = (string) preg_replace( '/[\s\-]/', '', trim( $postcode ) );
				break;
		}
	}

	$flags   = isset( $rule['flags'] ) && 'i' === $rule['flags'] ? 'i' : '';
	$matched = preg_match( '~\A(?:' . $rule['pattern'] . ')\z~' . $flags, $postcode );

	return false === $matched ? null : 1 === $matched;
}