Postal Code Validation - Canada only

Hi!

I’m looking to validate a postal code field for Canadian postal codes. I see this post about validating a field here Zipcode validation for Gravity Forms (5 digits, 2 approaches). · GitHub , however this looks to be 5 digit only for US codes. Has anyone done this for Canadian codes? Interestingly, in GF I can set the address field type to be ‘Canadian Address’, but this doesn’t do anything with regards to validation. Right now the postal code field can be a long string of any mix. An example Canadian postal code would be ‘N1G 3L5’. Any tips or recommendations are greatly appreciated. Thank you

Cheers

Tom

Hi Tom. You can use the gform_field_validation filter to validate that the postcode provided is a valid Canadian postcode. Here are the rules I found for the postcode validation:

  • ^[ABCEGHJKLMNPRSTVXY]: First character must be one of the allowed alphabetic characters (A, B, C, E, etc.).
  • \d: Second character must be a digit.
  • [ABCEGHJKLMNPRSTVWXYZ]: Third character must be an allowed alphabetic character.
  • ?: Allows an optional space.
  • \d: Fifth character must be a digit.
  • [ABCEGHJKLMNPRSTVWXYZ]: Sixth character must be an allowed alphabetic character.
  • \d: Seventh character must be a digit.
  • /i: Makes the regex case-insensitive.

I used that regex with the gform_field_validation filter. Here’s the code:

// Address field 3 in form 177
add_filter( 'gform_field_validation_177_3', function( $result, $value, $form, $field ) {
	// Part 5 of the address field is the postcode
    $postcode = rgar( $value, $field->id . '.5' ); 

    // Define the Canadian postcode regex
    $regex = '/^[ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ] ?\d[ABCEGHJKLMNPRSTVWXYZ]\d$/i';

    // Validate the postcode against the regex
    if ( ! preg_match( $regex, $postcode ) ) {
        // If invalid, set the result to false and add a custom validation message
        $result['is_valid'] = false;
        $result['message']  = 'Please enter a valid Canadian postcode (e.g., A1A 1A1).';
    }

    return $result;
}, 10, 4 );

That will validate the address field ID 3 in form 177. See the advice here for how to add this PHP code to your site:

1 Like

Hi Chris,

Thank you for the very detailed response. This is great. We’ll test this out!

Best,

Tom

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.