WooCommerce結帳頁限制電話號碼

由於有串接宅急便的api,電話號碼的數值有限制,我做了以下的規則

  • 只能打數字
  • 09開頭一定要10位數
  • 最多限制10碼

由於宅急便的api限制很多,就連台灣人常用的分機碼 # 也不能用,同時也有限制長度

function custom_checkout_field_validation() {
    ?>
    <script type="text/javascript">
        jQuery(document).ready(function($){
            // 選擇需要檢查的欄位
            const phoneFields = ['#billing_phone', '#shipping_phone'];

            phoneFields.forEach(function(field) {
                $(field).on('input', function() {
                    let value = $(this).val();
                    // 只允許輸入數字
                    const filteredValue = value.replace(/\D/g, '');  // 移除所有非數字字符
                    
                    // 檢查是否有非數字字符
                    if (value !== filteredValue) {
                        // 顯示錯誤訊息
                        $(this).next('.error-message').remove();
                        $(this).after('<span class="error-message" style="color:red;">請輸入數字,如有分機請於地址後備註</span>');
                    } else {
                        // 移除錯誤訊息
                        $(this).next('.error-message').remove();
                    }

                    // 將過濾後的值回填到欄位
                    $(this).val(filteredValue);
                });
            });

            // 結帳提交時的驗證
            $('form.checkout').on('checkout_place_order', function(e){
                let isValid = true;
                phoneFields.forEach(function(field) {
                    const value = $(field).val();
                    const startsWith09 = value.startsWith('09');
                    
                    // 檢查以 "09" 開頭的電話號碼是否為10碼
                    if (startsWith09 && value.length !== 10) {
                        isValid = false;
                        $(field).next('.error-message').remove();
                        $(field).after('<span class="error-message" style="color:red;">09開頭的電話號碼必須填滿10碼</span>');
                    }
                    // 檢查所有電話號碼是否只包含數字且不超過10碼
                    else if (!/^\d{1,10}$/.test(value)) {
                        isValid = false;
                        $(field).next('.error-message').remove();
                        $(field).after('<span class="error-message" style="color:red;">請輸入數字,如有分機請於地址後備註</span>');
                    }
                });

                if (!isValid) {
                    e.preventDefault(); // 阻止表單提交
                    alert('請確保09開頭的電話號碼為10碼,並且輸入數字,如有分機請於地址後備註');
                    return false; // 返回false以確保表單不會提交
                }
            });
        });
    </script>
    <?php
}
add_action('wp_footer', 'custom_checkout_field_validation');
瀏覽次數:19