WooCommerce订单备注禁用特殊字符代码如何取消字段必填校验
问题原因
原代码的验证条件使用了||(或逻辑),只要字段为空就会触发报错,因此强制所有参与校验的字段为必填,不符合非必填字段(如订单备注)留空的需求。
修改思路
仅当字段不为空的时候,才校验是否仅含字母;空值直接跳过校验,不做必填限制。只需调整非必填字段的判断逻辑即可,默认必填的账单/配送姓名字段可以保留原有逻辑。
修改后完整代码
/* 结算字段仅允许输入字母字符,保留非必填字段可选属性 */ add_action('woocommerce_checkout_process', 'wh_alphaCheckCheckoutFields'); function wh_alphaCheckCheckoutFields() { $billing_first_name = filter_input(INPUT_POST, 'billing_first_name'); $billing_last_name = filter_input(INPUT_POST, 'billing_last_name'); $order_comments = filter_input(INPUT_POST, 'order_comments'); $shipping_first_name = filter_input(INPUT_POST, 'shipping_first_name'); $shipping_last_name = filter_input(INPUT_POST, 'shipping_last_name'); $ship_to_different_address = filter_input(INPUT_POST, 'ship_to_different_address'); // 账单姓名字段为WooCommerce默认必填,保留原有校验逻辑 if (empty(trim($billing_first_name)) || !ctype_alpha($billing_first_name)) { wc_add_notice(__('仅允许在<strong>账单名</strong>中输入字母字符。'), 'error'); } if (empty(trim($billing_last_name)) || !ctype_alpha($billing_last_name)) { wc_add_notice(__('仅允许在<strong>账单姓</strong>中输入字母字符。'), 'error'); } // 订单备注为非必填,仅当用户填写了内容时才校验格式 if (!empty(trim($order_comments)) && !ctype_alpha($order_comments)) { wc_add_notice(__('仅允许在<strong>配送说明</strong>中输入字母字符。'), 'error'); } // 勾选使用不同配送地址时的字段校验 if (!empty($ship_to_different_address)) { // 配送姓名字段为默认必填,保留原有校验逻辑 if (empty(trim($shipping_first_name)) || !ctype_alpha($shipping_first_name)) { wc_add_notice(__('仅允许在<strong>配送名</strong>中输入字母字符。'), 'error'); } if (empty(trim($shipping_last_name)) || !ctype_alpha($shipping_last_name)) { wc_add_notice(__('仅允许在<strong>配送姓</strong>中输入字母字符。'), 'error'); } } }
可选拓展
如果需要把原本默认必填的姓名字段也改成可选,或者需要支持中文、空格、连字符等特殊字符,可以做如下调整:
- 调整字段校验逻辑:将对应判断规则中的
empty(trim(xxx)) ||替换为!empty(trim(xxx)) && - 替换字符校验规则:将
ctype_alpha($xxx)替换为preg_match('/^[\p{L}\s-]+$/u', $xxx),即可支持多语言字母、空格和短横线。
内容的提问来源于stack exchange,提问作者Lee
相关产品推荐
相关产品推荐

