自定义验证在版本4.1.1中的联系表格7中不起作用

Jit*_*mor 4 validation wordpress wordpress-plugin contact-form contact-form-7

我必须在联系表单7中创建一个带有自定义验证字段的表单.它不适用于Contact Form 7的最新版本(4.1.1),但使用的是旧版本.

我创建了一个从表单中获取优惠券代码的字段.如果优惠券是从"HIP"启动的,我想验证条目.我的代码如下:

add_filter( 'wpcf7_validate_text', 'your_validation_filter_func', 999, 2 );
add_filter( 'wpcf7_validate_text*', 'your_validation_filter_func', 999, 2 );


function your_validation_filter_func( $result, $tag ) {
$type = $tag['type'];
$name = $tag['name'];      
if ( 'coupon_code' == $name ) {
$the_value = $_POST[$name];

        $myresult = substr($the_value, 0, 3);
        if($myresult=="HIP")
        {
            $result['valid'] = true;
        }
        else
        {
            $result['valid'] = false;
            $result['reason'][$name] = "Not a valid coupon code";
        }
}

return $result;
}
Run Code Online (Sandbox Code Playgroud)

请给我一些建议.

小智 6

我在联系表格7自定义验证方面遇到了类似的问题.最后登陆这篇文章,并在官方定制表格7自定义验证链接在这里:http://contactform7.com/2015/03/28/custom-validation/.

在早期版本的CF7上运行的代码所需的唯一更新是替换以下代码行:

$result['reason'][$name] = 'Your custom validation message goes here';
Run Code Online (Sandbox Code Playgroud)

有:

$result->invalidate( $tag, "Your custom validation message goes here." );
Run Code Online (Sandbox Code Playgroud)


小智 5

当我用 4.1.1 更新联系表 7 时,我也遇到了这个问题。在最新版本的联系表单 7 中,旧的自定义验证代码不起作用。

因此,经过大量研究,我找到了解决方案。因此,在您的情况下,您需要按以下方式更改代码。可能对你有帮助。

add_filter('wpcf7_validate_text', 'your_validation_filter_func', 999, 2);
add_filter('wpcf7_validate_text*', 'your_validation_filter_func', 999, 2);

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

if ('coupon_code' == $name) {

    $the_value = $_POST[$name];

    $myresult = substr($the_value, 0, 3);
    if ($myresult == "HIP") {
        $result['valid'] = true;
    } else {
        $result->invalidate($tag, wpcf7_get_message('invalid_coupon_code'));
    }
}

return $result;
}

add_filter('wpcf7_messages', 'mywpcf7_text_messages');

function mywpcf7_text_messages($messages) {
return array_merge($messages, array(
    'invalid_coupon_code' => array(
        'description' => __("Coupon is invalid", 'contact-form-7'),
        'default' => __('Coupon seems invalid.', 'contact-form-7')
)));
}
Run Code Online (Sandbox Code Playgroud)