问题
I want the user to enter a minimum of 7 numbers for their phone number in the Woocommerce checkout. The function below works but it includes spaces, so if user enter 6 numbers with 1 space it counts it as 7. How Can I change the function so that it only counts numbers not spaces so that the user has to enter a minimum of 7 numbers.
// validation for Billing Phone checkout field
add_action('woocommerce_checkout_process', 'custom_validate_billing_phone');
function custom_validate_billing_phone() {
$is_correct = preg_match('/^[0-9 \-]{7}/i', $_POST['billing_phone']);
if ( $_POST['billing_phone'] && !$is_correct) {
wc_add_notice( __( 'Phone Number must be <strong>minimum 7 numbers</strong>.' ), 'error' );
}
}
回答1:
I figured out the solution.
$is_correct = preg_match('/^[0-9\D]{7}/i', $_POST['billing_phone']);
回答2:
You can use the following regex. It only Count the digits:
^(?:\D*?\d\D*?){7}$
It starts from start of string, then creates a non capturing Group, that matches optional any number of non digit, digit and optional any number of non digit. It will require exactly 7 of that.
This means, it only Counts the digits and ignore non digits in the Count.
Examples of match:
1234567
1 23 45 67
123-4567
Example of non-match:
123 456
12-34-56-78
回答3:
Change preg_match
line with this line:
$is_correct = preg_match('/^[0-9\-]{7}/i', $_POST['billing_phone']);
That should work.
来源:https://stackoverflow.com/questions/53440386/minimum-phone-numbers-digits-woocommerce-checkout