问题描述
我在 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 );