2017-09-27 87 views
0

我想實現一個字段名稱VoucherNumber的文本字段驗證,要求代碼處於'WWV-'後面跟4個數字的特定模式。 我成功地使用以下表達式^[W]WV-[0-9][0-9][0-9][0-9]在google文檔上實現了這一點。驗證聯繫表7中的自定義代碼的問題

我研究了各種答案,並試圖在functions.php中添加此代碼,但它沒有奏效。它只會顯示錶單正在發送(旋轉輪),但即使在5分鐘後也不會發送。

add_filter('wpcf7_validate_text*', 'validate_voucher_number', 20, 2); 
    function validate_voucher_number($result, $tag) { 
    $tag = new WPCF7_FormTag($tag); 
    if ('VoucherNumber' == $tag->name) { 
     $VoucherNumber = isset($_POST['VoucherNumber']) ? trim($_POST['VoucherNumber']) : ''; 
     if (! preg_match ("^[W]WV-[0-9][0-9][0-9][0-9]" , $VoucherNumber)){ 
     $result->invalidate($tag, "Voucher number is invalid"); 
    } 
    } 
return $result; 
    } 

回答

0

只要確保你的字段名稱充值卡號碼,並嘗試這種代碼:

add_filter('wpcf7_validate_text', 'vouchervalidation', 20, 2); 

function vouchervalidation($result, $tag) { 
if ('VoucherNumber' == $tag->name) { 
    $VoucherNumber = isset($_POST['VoucherNumber']) ? trim($_POST['VoucherNumber']) : ''; 

    if (! preg_match ("^[W]WV-[0-9][0-9][0-9][0-9]" , $VoucherNumber)){ 
      $result->invalidate($tag, "Voucher number is invalid"); 
    } 
} 

return $result; 
} 
+0

我改變的字段名「代金券」爲簡單起見,但事實證明這個代碼不驗證領域它也會接受無效響應(忽略前三個字母的大小寫鎖定,即使它與驗證規則不匹配也會接受任何響應)。我將代碼插入到functions.php文件的末尾,並嘗試將其粘貼到起始位置,但仍無法驗證。 –

+0

您的preg_match是否正確,因爲我懷疑它一定不會進入您的if條件 –

+0

我正在使用此代碼'add_filter('wpcf7_validate_text','vouchervalidation',20,2); function vouchervalidation($ result,$ tag){ if('voucher'== $ tag-> name){ $ voucher = isset($ _POST ['voucher'])? trim($ _POST ['voucher']):''; if(!preg_match(「^ [W] WV- [0-9] [0-9] [0-9] [0-9]」,$ voucher)){ $ result-> invalidate($ tag ,「憑證號碼無效」); } } return $ result; }' –