Validate the Checkout Phone Number Format
Rejects billing phone numbers that contain letters or too few digits on the classic checkout, so you get numbers you can actually call.
Opens WPIDE on
Code
add_action( 'woocommerce_after_checkout_validation', function ( $data, $errors ) {
$min_digits = 7; // Minimum number of digits.
if ( empty( $data['billing_phone'] ) ) {
return;
}
$phone = (string) $data['billing_phone'];
$digits = preg_replace( '/\D/', '', $phone );
if ( preg_match( '/[^0-9\s\-\.\(\)\+]/', $phone ) || strlen( $digits ) < $min_digits ) {
$errors->add( 'validation', 'Please enter a valid phone number.' );
}
}, 10, 2 );
Notes
Change $min_digits to suit your country. Spaces, dashes, dots, brackets and a leading + are allowed.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.