Skip to content

Instantly share code, notes, and snippets.

@webdevsuperfast
Last active September 20, 2020 03:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save webdevsuperfast/43d1d5a68ac2f7e8232623bba736e180 to your computer and use it in GitHub Desktop.
Save webdevsuperfast/43d1d5a68ac2f7e8232623bba736e180 to your computer and use it in GitHub Desktop.
Validate US ZIP Code with Zippopotamus and Contact Form 7
<?php
/**
* Functions
*
* @package Twenty Twenty Child
* @since 1.0
* @link https://rotsenacob.com
* @author Rotsen Mark Acob <rotsenacob.com>
* @copyright Copyright (c) 2020, Rotsen Mark Acob
* @license http://opensource.org/licenses/gpl-2.0.php GNU Public License
*
*/
// Validate US ZIP Code Format
function validate_zipcode( $zipcode ) {
return preg_match( '/^[0-9]{5}(?:-[0-9]{4})?$/i', $zipcode ); // @link https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch04s14.html
}
add_filter( 'wpcf7_validate_text', 'tc_validate_text', 20, 2 );
add_filter( 'wpcf7_validate_text*', 'tc_validate_text', 20, 2 );
function tc_validate_text( $result, $tag ) {
$type = $tag['type'];
$name = $tag['name'];
$value = $_POST[$name];
if ( $name == 'zipcode' ) {
if ( validate_zipcode( $value ) ) {
} else {
$result->invalidate( $tag, wpcf7_get_message( 'invalid_zip_code' ) );
}
}
return $result;
}
// Display Custom Messages
add_filter( 'wpcf7_messages', 'tc_wpcf7_messages' );
function tc_wpcf7_messages( $messages ) {
return array_merge( $messages, array(
'invalid_zip_code' => array(
'default' => __( 'Invalid US ZIP Code, ZIP Code must have 5 digit numbers.' )
)
) );
}
// Intercept form data to validate zip codes with Zippopotamus API before sending
add_filter( 'wpcf7_before_send_mail', function( $form, &$abort, $submission ) {
if ( $abort === TRUE ) {
return;
}
$data = $submission->get_posted_data();
$zipcode = sanitize_text_field( $data['zipcode'] );
$response = wp_remote_get( esc_url_raw( 'https://api.zippopotam.us/us/' . $zipcode ) );
$body = wp_remote_retrieve_body( $response );
$result = json_decode( $body, true );
if ( is_wp_error( $response ) || empty( $result ) ) {
$abort = TRUE;
$submission->set_response('You entered an invalid USA ZIP code');
$submission->set_status('api_failed');
}
}, 10, 3 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment