【发布时间】:2021-03-13 15:39:07
【问题描述】:
我在 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', 'custom_postcode_validation_filter', 10, 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*', 'custom_postcode_validation_filter', 10, 2 );
add_filter( 'wpcf7_validate_text', 'custom_postcode_validation_filter', 10, 2 );
}
}
它仍然无法正常工作。我错过了什么?
我还希望,如果用户填写的字段没有大写字母,文本字段会自动转换它们。
感谢任何建议!
【问题讨论】:
-
你的正则表达式是 4 个数字,然后是一个反斜杠,接下来的两个字符不是 a-Z。
-
如果你想匹配 4 个数字然后 2 个字母,你会想要类似 '/^([0-9]{4}[a-zA-Z]{2}) $/'
-
我试过了,但不幸的是它没有用。
标签: php wordpress contact-form-7 add-filter