diff --git a/includes/class-wc-checkout.php b/includes/class-wc-checkout.php index 4d92bbca60e..036c4ba612c 100644 --- a/includes/class-wc-checkout.php +++ b/includes/class-wc-checkout.php @@ -747,7 +747,7 @@ class WC_Checkout { $field_label = isset( $field['label'] ) ? $field['label'] : ''; if ( $validate_fieldset && - ( isset( $field['type'] ) && 'country' === $field['type'] ) && + ( isset( $field['type'] ) && 'country' === $field['type'] && '' !== $data[ $key ] ) && ! WC()->countries->country_exists( $data[ $key ] ) ) { /* translators: ISO 3166-1 alpha-2 country code */ $errors->add( $key . '_validation', sprintf( __( "'%s' is not a valid country code.", 'woocommerce' ), $data[ $key ] ) ); diff --git a/tests/php/includes/class-wc-checkout-test.php b/tests/php/includes/class-wc-checkout-test.php index 3a6867a1a5c..0a9b87a645f 100644 --- a/tests/php/includes/class-wc-checkout-test.php +++ b/tests/php/includes/class-wc-checkout-test.php @@ -93,6 +93,30 @@ class WC_Checkout_Test extends \WC_Unit_Test_Case { $this->assertEmpty( $errors->get_error_message( 'shipping_country_validation' ) ); } + /** + * @testdox 'validate_posted_data' doesn't add errors for empty billing/shipping countries. + * + * @testWith [true] + * [false] + * + * @param bool $ship_to_different_address True to simulate shipping to a different address than the billing address. + */ + public function test_validate_posted_data_does_not_add_error_for_empty_country( $ship_to_different_address ) { + $_POST = array( + 'billing_country' => '', + 'shipping_country' => '', + 'ship_to_different_address' => $ship_to_different_address, + ); + $data = $_POST; // phpcs:ignore WordPress.Security.NonceVerification.Missing + + $errors = new WP_Error(); + + $this->sut->validate_posted_data( $data, $errors ); + + $this->assertEmpty( $errors->get_error_message( 'billing_country_validation' ) ); + $this->assertEmpty( $errors->get_error_message( 'shipping_country_validation' ) ); + } + /** * @testdox 'validate_checkout' adds a "We don't ship to country X" error but only if the country exists. *