Limit Checkout Phone field to 10 numbers – Validation

/**
 * You can add a custom placeholder to add a hint for your CUs what you expect.
 * Our hooked in function - $fields is passed via the filter.
 */
add_filter( 'woocommerce_checkout_fields', function ( $fields ) {
	$fields['billing']['billing_phone']['placeholder'] = '09XXXXXXXXX';
	return $fields;
} );

/**
 * Process the checkout.
 * Validation for phone field this will throw an error message.
 */
add_action( 'woocommerce_checkout_process', function () {
	global $woocommerce;
	// Check if set, if its not set add an error. This one is only requite for companies.
	if ( ! preg_match( '/^[0-9]{10}$/D', $_POST['billing_phone'] ) ) {
		wc_add_notice( 'The Phone should contain only 10 digits', 'error' );
	}
} );

Leave a Comment