From 5256cf47dcc0c3a164652a025e274c2a50e65bfe Mon Sep 17 00:00:00 2001 From: jamez Date: Tue, 9 Feb 2016 12:39:09 -0500 Subject: [PATCH] Canada Postal code validation Added Postal Code validation for Canada (country-code=CA). Also added to the validation unit test for valid and invalid postal code examples. --- includes/class-wc-validation.php | 4 ++++ tests/unit-tests/util/validation.php | 12 +++++++++++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/includes/class-wc-validation.php b/includes/class-wc-validation.php index 0fbca96ef2b..491a5f7633b 100644 --- a/includes/class-wc-validation.php +++ b/includes/class-wc-validation.php @@ -70,6 +70,10 @@ class WC_Validation { case 'US' : $valid = (bool) preg_match( '/^([0-9]{5})(-[0-9]{4})?$/i', $postcode ); break; + case 'CA' : + // CA Postal codes cannot contain D,F,I,O,Q,U and cannot start with W or Z. https://en.wikipedia.org/wiki/Postal_codes_in_Canada#Number_of_possible_postal_codes + $valid = (bool) preg_match( '/^([ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ])([\ ])?(\d[ABCEGHJKLMNPRSTVWXYZ]\d)$/i', $postcode ); + break; default : $valid = true; diff --git a/tests/unit-tests/util/validation.php b/tests/unit-tests/util/validation.php index ae9518dbcb6..4ca3ccb14bb 100644 --- a/tests/unit-tests/util/validation.php +++ b/tests/unit-tests/util/validation.php @@ -82,8 +82,18 @@ class Validation extends \WC_Unit_Test_Case { array( false, \WC_Validation::is_postcode( '99999 999', 'BR' ) ), array( false, \WC_Validation::is_postcode( '99999-ABC', 'BR' ) ) ); + + $ca = array( + array( true, \WC_Validation::is_postcode( 'A9A 9A9', 'CA' ) ), + array( true, \WC_Validation::is_postcode( 'A9A9A9', 'CA' ) ), + array( true, \WC_Validation::is_postcode( 'a9a9a9', 'CA' ) ), + array( false, \WC_Validation::is_postcode( 'D0A 9A9', 'CA' ) ), + array( false, \WC_Validation::is_postcode( '99999', 'CA' ) ), + array( false, \WC_Validation::is_postcode( 'ABC999', 'CA' ) ), + array( false, \WC_Validation::is_postcode( '0A0A0A', 'CA' ) ) + ); - return array_merge( $generic, $gb, $us, $ch, $br ); + return array_merge( $generic, $gb, $us, $ch, $br, $ca ); } /**