如何验证 WordPress functions.php 文件中的联系表 7 字段

How to validate contact form 7 field from functions.php file in WordPress

我在联系表 7 中有一个数字字段。它必须是 11 位数字,前两位数字必须是 24 或 42。请告诉我如何从 functions.php 文件中执行此操作。这是我的正则表达式 ^(24|42)\d{9}$ 。但是我不能在 functions.php 文件

上使用它

检查 http://contactform7.com/2015/03/28/custom-validation/ 以获得有关表单验证的一般信息。假设您的字段有 type="number"name="eleven-digits",您的过滤器可能如下所示:

add_filter( 'wpcf7_validate_number', function( $result, $tag ) {
    $tag = new WPCF7_Shortcode( $tag );
    if ( $tag->name = 'eleven-digits' && preg_match( '^(24|42)\d{9}$', $result ) ) {
        return true;
    }

    return false;
} );

如果你想要更详细的答案,你应该在你的问题中添加更多细节。

答案在这里

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

function custom_number( $result, $tag ) {
$tag = new WPCF7_Shortcode( $tag );

if ( $tag->name = 'eleven-digits' ){
    $number = isset( $_POST['eleven-digits'] ) ? trim( $_POST['eleven-digits'] ) : '';
    if (!preg_match( '/^(24|42)\d{9}/', $number )) {
       $result->invalidate( $tag, "Enter correct number." );
    }
}
return $result;
}

我在末尾添加了表达式 $ 以允许超过 9 位数字,它是这样的:

/^(24|42)\d{9}$/