如何在 CF7

问题描述

我在 CF7 中有一个文本字段,我想验证用户输入是否为 4 位数字和 2 个字符,例如:1234AB(没有空格和大写字母)。

这是我已经拥有的,但它不起作用:

function custom_postcode_validation_filter($result,$tag){

    $name = $tag->name;

    if($name == 'ba-postcode'){

        $bapostcode = $_POST['ba-postcode'];

        if($bapostcode != '') {

            if(!preg_match('/^([0-9]{4})\\([^a-Z]{2})$/',$bapostcode)) {

                $result->invalidate( $tag,"Vul alstublieft een geldige postcode in." );

            }

        }

    }

    return $result;
}   

add_filter( 'wpcf7_validate_text*','custom_postcode_validation_filter',10,2 );
add_filter( 'wpcf7_validate_text',2 );

我认为这可能与此行有关: if(!preg_match('/^([0-9]{4})\\([^a-Z]{2})$/',$bapostcode)) {

所以我在得到一些帮助后更新了答案。这就是我现在所拥有的:

function custom_postcode_validation_filter($result,$tag){

    $name = $tag->name;

    if($name == 'ba-postcode'){

        $bapostcode = $_POST['ba-postcode'];

        if($bapostcode != '') {

            $regex = "/^[1-9][0-9]{3} ?(?!sa|sd|ss)[a-z]{2}$/i";

if(!preg_match( $regex,$bapostcode)) {
    $result->invalidate( $tag,"Vul alstublieft een geldige postcode in." );
}

    return $result;
}   

add_filter( 'wpcf7_validate_text*',2 );
    }
 }

它仍然无法正常工作。我错过了什么?

我还希望如果用户填写的字段没有大写字母,文本字段会自动转换它们。

感谢任何建议!

解决方法

试试这个正则表达式,我在一个荷兰网站上用过,它有相似的结构。

function custom_postcode_validation_filter( $result,$tag ){

    if( 'ba-postcode' == $tag->name ){

        // Get postcode field
        $bapostcode = isset( $_POST['postcode'] ) ? trim( $_POST['postcode'] ) : '';

        // Check postcode is set
        if($bapostcode != '') {

            // match postcodes 1234AB
            $regex = "/^[1-9][0-9]{3}(?!sa|sd|ss)[a-z]{2}$/i";

            // validate postcode
            if( !preg_match( $regex,$bapostcode ) ) {
                $result->invalidate( $tag,"Vul alstublieft een geldige postcode in." );
            }

        }   
    }

    return $result;
}
add_filter( 'wpcf7_validate_text*','custom_postcode_validation_filter',10,2 );
add_filter( 'wpcf7_validate_text',2 );
,

好的,我用这段代码完成了:

function custom_postcode_validation_filter($result,$tag){

    $name = $tag->name;

    if($name == 'ba-postcode'){

        $bapostcode = $_POST['ba-postcode'];

        if($bapostcode != '') {

            if(!preg_match('/^([1-9]{1})([0-9]{3})([\s]{0,1})([a-zA-Z]{2})$/',$bapostcode)) {

                $result->invalidate( $tag,"Vul alstublieft een geldige postcode in." );

            }

        }

    }

    return $result;
}   

add_filter( 'wpcf7_validate_text*',2 );

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...