I have added a custom code to validate the phone numbers to be 10 digits on checkout fields.

Here is the code

add_action('woocommerce_checkout_process', 'phone_number_validation');

function phone_number_validation() {

global $woocommerce;

if ( ! (preg_match('/^[0-9]{10}$/D', $_POST['billing_phone'] ))){

wc_add_notice( "Incorrect Phone Number! Please enter valid 10 digits phone number"  ,'error' 
);

}
}

As i need alternate numbers in billing field we added one more phone number field(which is optional).

I used the same code for alternate field validation with 10 digits but i cant able to submit form since it ask me to enter phone number in that alternate field also.

Since its a optional fields i need to skip validation if no phone number entered. on other hand if phone number is entered on that field it should be validated for minimum 10 digit.

Recommended Answers

All 2 Replies

This is completely irrelevant, but perhaps it will help in the future. PHP has a built-in filter_var() function that automatically validates that an appropriately formatted email, URL, etc. have been typed in. The only reason I bring this up is because for some reason I thought that phone numbers might be included in that function, so I checked, but alas they're not.

You can change line 7 to be:

if (!empty($_POST['billing_phone']) && ! (preg_match('/^[0-9]{10}$/D', $_POST['billing_phone'] ))){

This should only show the error message if it's both not empty and doesn't match the criteria.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.