2016-02-12 69 views
0

我已經在我的Wordpress站點中使用了「contact-form-7」,我們如何在名稱字段上應用驗證,以便它只接受字符串作爲字符數字字符串/號碼 將不會被允許。要在Wordpress中的姓名字段上應用驗證

function wpcf7_is_user_name($name) 
{ 
$result = preg_match('/^[A-Za-z .]*$/', $name); 
    return apply_filters('wpcf7_is_user_name', $result, $name); 
} 

我在上面Formatting.php頁提到的代碼添加,但它不工作。可以請人協助我工作第一次在Word新聞。

+0

應用過濾器只需要2個參數:https://developer.wordpress.org/reference/functions/apply_filters/ – Tdelang

回答

0

這裏的工作示例如何在聯繫表格7中實施一些自定義驗證和返回錯誤:

假設我們在我們的形式有此輸入字段:

<p>Your Name (required)<br /> 
[text* your-name] </p> 

我們將它添加到我們的主題的functions.php文件:

// our function will be called for all text and text* input fields 
add_filter('wpcf7_validate_text', 'wpcs4948_validation_func', 10, 2); 
add_filter('wpcf7_validate_text*', 'wpcs4948_validation_func', 10, 2); 


function wpcs4948_validation_func($result, $tag) { 
    $type = $tag['type']; 
    $name = $tag['name']; 

    // check to see if the input field name matches 
    if ('your-name' == $name) { 
    $the_value = $_POST[$name]; 

    // use a regular expression to compare the value against 
    if (preg_match('/^\D*$/', $the_value)==0) { 
     // the value does not match the regular expression 
     // invalidate the form submission and display this error message 
     $result->invalidate($tag, "Name must contain only letters."); 
     } 
    } 

return $result; 
} 

如果your-name字段包含數字這將返回一個錯誤。

請注意,我沒有使用您建議的正則表達式/^[A-Za-z .]*$/這是因爲該正則表達式會拒絕在其中包含破折號和句點的名稱,這可能不是您想要用於「名稱」字段的名稱。然而,如果你真的有興趣過濾一個「用戶名」字段只包含字母,比你可以用/^[A-Za-z .]*$/替換/^\D*$/

希望這有助於!