Contact Form 7 正则表达式验证

Contact Form 7 Regular Expression Validation

我正在尝试将正则表达式验证添加到 Contact Form 7 'last-name' 字段,该字段将允许使用连字符连接的名称。我已经研究并编写了一个函数来实现这一点,但它似乎没有用。任何帮助将不胜感激。

这是我编写并放在 functions.php 文件中的函数...

add_filter('wpcf7_validate_text', 'custom_text_validation', 20, 2);
add_filter('wpcf7_validate_text*', 'custom_text_validation', 20, 2);

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

    if($name == 'last-name') {
        $value = $_POST[$name];
        if(!preg_match('[a-zA-Z\-]', $value)){
            $result->invalidate($tag, "Invalid characters");
        }
    }
    return $result;
}

尝试否定它

if(preg_match('/[^a-z\-]/i', $value)){

我也将其更新为使用 /i,这将忽略大小写

所以我认为我们首先需要看的是第 5th 和 6th 行。根据 CF7 documentation$tag 参数实际上 returns 是一个对象而不是数组。

这意味着 $tag['name']$tag['type'] 实际上应该是 $tag->name$tag->type.

第二个要解决的问题是您的正则表达式,现在是阅读 Falsehoods Programmers Believe about Names 的好时机。基本上,简而言之,如果标准是 MixedAlpha 和破折号,则有很多姓氏将不匹配。

但是,如果您打算剔除一部分潜在用户,我建议您使用 maček's basic regex listed on this SO answer,因为它至少会包含更多潜在的有效姓氏。

这会将您的函数变成如下所示:

add_filter('wpcf7_validate_text', 'custom_text_validation', 20, 2);
add_filter('wpcf7_validate_text*', 'custom_text_validation', 20, 2);

function custom_text_validation($result, $tag) {
    $type = $tag->type; //object instead of array
    $name = $tag->name; //object instead of array

    if($name == 'last-name') {
        $value = $_POST[$name];
        if(!preg_match("/^[a-z ,.'-]+$/i", $value )){ //new regex statement
            $result->invalidate($tag, "Invalid characters");
        }
    }
    return $result;
}