[英]Force 8 digits in phone number WooCommerce
在丹麥,所有電話號碼都是 8 位數字。 我們想強制所有訂單為 8 位數,以防止交付時出現錯誤和其他問題。 永遠不會少,永遠不會更多。 如果不是 8 位數字,他們應該收到警告。
// You can add a custom placeholder to add a hint for your CUs what you expect
add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields2' );
// Our hooked in function - $fields is passed via the filter!
function custom_override_checkout_fields2( $fields ) {
$fields['billing']['billing_phone']['placeholder'] = 'Add 8 digits';
return $fields;
}
/****************************************************************/
/* VALIDATION FOR PHONE FIELD THIS WILL THROW AN ERROR MESSAGE */
/****************************************************************/
/**
* Process the checkout
**
add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');
function my_custom_checkout_field_process() {
global $woocommerce;
// Check if set, if its not set add an error. This one is only requite for companies
if ( ! (preg_match('/^[0-9]{8}$/D', $_POST['billing_phone'] ))){
wc_add_notice( "Phone number must be 8 digits" ,'error' );
}
}
不幸的是,它不起作用。 數字仍然可以是任何東西。
在您的帖子中使用 strlen。 然后評估它是否等於您想要的長度。
function my_custom_checkout_field_process() {
global $woocommerce;
// Check if set, if its not set add an error. This one is only requite for companies
$len = strlen($_POST['billing_phone']);
if($len !== 8){
wc_add_notice( "Phone number must be 8 digits" ,'error' );
}
}
如果您還希望它匹配數字,請使用is_numeric()
或!is_numeric()
$len = strlen($_POST['billing_phone']);
if($len !== 8)){
wc_add_notice( "Phone number must be 8 digits" ,'error' );
if(!is_numeric($_POST['billing_phone'])){
wc_add_notice( "Phone number must be number" ,'error' );
}
}
如果丹麥使用了特定模式,您還可以將輸入設置為tel
類型並添加模式,這將有助於在支持 html 5 的瀏覽器上提交之前進行格式化
<input type="tel" id="phone" name="phone" pattern="[0-9]{8}" required>
數字小於 8 時出現 OUTPUT 錯誤:
OUTPUT 超過 8 個錯誤:
OUTPUT 錯誤(非數字時):
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.