The correct format of the buyer’s contact phone number is often important for confirming an order, sending notifications to customers, transferring data to a transport company, and filtering out fake orders. However, customers enter their numbers differently or even add a set of letters to the field. To avoid confusion, you need phone number validation on the WooCommerce Checkout page. This can be done automatically by a plugin or manually by code.

Installing the phone number verification plugin

The easiest option is to install a special Speedplus Check Woo Phone plugin, which checks the buyer’s phone number on the WooCommerce Checkout page against your rules: phone number length; characters used in the number; the mandatory beginning of the phone number.

You can buy the plugin from the link.

The demo version of the plugin can be tested here.

Checking a phone number with a code

To begin with, you should decide on the validation parameters that affect the following sections of code:

  • number length
  • allowed characters
  • permanent (mandatory) part
  • placeholder (hint)
  • error message

Add the following PHP code to the functions.php file of your active theme on your WordPress site to implement the function to parse the entered phone number against strict parameters.

// Checking entered phone number's format at Checkout
add_action('woocommerce_checkout_process', 'phone_check2_speedplus');
function phone_check2_speedplus() {
	// Phone entered?
	if ( !empty( $_POST['billing_phone'] ) ) {
		$number = $_POST['billing_phone'];
		$length = strlen($number);
		// We check 13 characters in the number, the mandatory beginning is +380 and 9 more digits 
		if (($length == 13) && (preg_match('/\+380[1-9]\d{8}\b/', $number))) {
			// The phone number matches the format
		}
		// In case of an error, we display a notification
		else {
			// Error text
			wc_add_notice( '<strong>' . sprintf( __("Please enter a phone number in international format. Example: +380951113322.") ) . '</strong>', 'error' );
		}
	}
}

After that, you may want to add the following code to display a placeholder in an empty phone field.

// Add Phone placeholder at Checkout page
add_filter( 'woocommerce_checkout_fields' , 'speedplus_overrides_checkout_fields', 20, 1 );
function speedplus_overrides_checkout_fields( $fields ) {
    $fields['billing']['billing_phone']['placeholder'] = '+380632221133';
    return $fields;
}

This is how the verification of the phone number on the site will look like.

Custom WooCommerce phone number validation

We also recommend that you look at the article about the prohibition of Cyrillic or Latin in the fields of the WooCommerce checkout.

If you have any difficulties with the implementation of phone number validation, you can contact us on the Contacts page for help.

Leave a comment

Your email address will not be published.