Validate phone number in woocommerce checkout page

后端 未结 2 401
清歌不尽
清歌不尽 2021-01-16 18:36

I would like to add custom validation to the phone number in checkout page of woocommerce. How do I do this??

2条回答
  •  旧时难觅i
    2021-01-16 19:30

    In my opinion there's no need to override default Woocommerce fields, nor use Javascript validation.
    You can add a custom validation, that will be added to the Woocommerce's default billing phone field validation, hooking to an action triggered after submitting checkout.

    This is the code I just implemented for a client.

    // Custom 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]{6,20}$/', $_POST['billing_phone']);
        if ( $_POST['billing_phone'] && !$is_correct) {
            wc_add_notice( __( 'The Phone field should be between 6 and 20 digits.' ), 'error' );
        }
    }
    

    Of course, instead of my preg_match you can check anything else and adjust your conditional code to your needs.

    You can also add custom validation for other default fields, by checking on the right $_POST variable, or your own custom checkout fields, after you correctly set them up, of course, but this is another topic :)

    Hope this helps.

提交回复
热议问题